简体   繁体   中英

The relations not working properly in Laravel 5.4

I have a model something like these two

workflows.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class workflows extends Model
{
    //getWorkflows
    protected $table = 'workflows';

    function workFlowStates()
    {
        return $this->hasMany('App\Models\workflow_states','id','workflow_id');
    }
}

workflow_states.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;
class workflow_states extends Model
{
    //
    protected $table = 'workflow_states';

    function workFlows()
    {
        return $this->belongsTo('App\Models\workflows','workflow_id','id');
    }

}

When I try to do this in my controller

public function editworkflow($id)
    {
        $wf_model = new workflows;
        dd($wf_model::find($id));

    }

I am not able to see any of the relationships , I can only see the data from the workflows table.

Can some one help me out here

thanks

Try this :

public function editworkflow($id)
{
  echo workflows::with('workFlowStates')->find($id);
}

You don't to make a object while editing record. Like $wf_model = new workflows; You can make the query by just calling model.

This is because the data from a relationship is not eager loaded by default. It is only retrieved when you ask it to or called a relation.

So, in your code if you try to access the relation data after the find method, it will load the data from db and give it to you which is called lazy loading. Like this:

public function editworkflow($id)
{
    $wf_model = new workflows;
    dd($wf_model::find($id)->workFlowStates);

}

However, if you want to eager load the data you can use Eloquent's with function. But it will not be necessary for a single record as it won't make any difference.

Read this Eloquent eager loading .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM