Laravel 5.6尝试将一个模型的属性与另一个模型的属性分配

时间:2018-06-28 10:49:04

标签: laravel laravel-5.6

所以我有以下代码:

foreach($goods as &$good) {
        $good->steps = collect([]);

        $starting_steps = Step::select('id', 'availability_id', 'route_id')->get();

        foreach($starting_steps as $step) {
            $final_steps = Step::select('id', 'availability_id', 'route_id')                    ->where('availability_id', $step->availability_id)
                ->where('status', 'active')
                ->where('route_id', $step->route_id)
                ->where('id', '>', $step->id)
                ->limit(1)->get();

            if($final_steps->count()) {
                if($good->steps->isEmpty()) {
                    $good->steps = $final_steps;
                }
                else {
                    $good->steps->push($final_steps);
                }
            }
        }

        if($good->steps->count()) {
            foreach($good->steps as $step) {
                $leg = new Availabilities_goods_leg;
                $leg->availability_id = $step->availability_id;
                $leg->route_id = $step->route_id;
                $leg->good_id = $good->id;
                $leg->match = 1;
                $leg->save();
            }
        }
    }

在此行$leg->availability_id = $step->availability_id;上,我试图保存availability_id中包含的$step->availability_id,但是出现以下错误Property [availability_id] does not exist on this collection instance.

如果我放$leg->availability_id = 4,则一切正常,没有错误。 只有当我尝试使用$step->availability_id进行分配时,它才会收到错误。 我尝试通过进行$step->availability_id来查看dd($step->availability_id)是否具有任何价值。 那里可能出什么问题了?

谢谢!

2 个答案:

答案 0 :(得分:0)

由于某种原因,我设法找到错误,如果我将if($good->steps->isEmpty())更改为if(isset($good->steps)),则该错误有效。 也许有人觉得这很有用。

答案 1 :(得分:0)

isset official doc

isset()核心php函数,用于检查变量是否存在,这意味着null。 laravels收集方法检查给定的收集中是否包含元素。 isEmpty laravel doc

null-> isEmpty()不能阻止php引发错误,而isset()可以阻止