Display in VIEW of One to One relation in Laravel Relationship

白昼怎懂夜的黑 提交于 2021-02-10 11:52:35

问题


I am here again with a trouble understanding the correct way of doing Laravel Relationships

I have this User Model

 public function concessionaire()
{
    return $this->hasOne('App\Concessionaire', 'meternum', 'meternum');
}

and Concessionaire Model

 public function user()
{
    return $this->belongsTO('App\User', 'meternum', 'meternum');
}

But when I try to display it in my view. the concessionaire data fields does not display..

In my Controller I have this

$dataUser = User::where('usertype', '=', 'concessionaire')
                ->with('concessionaire')
                ->get();
    return view('admin.concessionaire',compact('dataUser'));

in my View

@foreach($dataUser as $User)
<td>
{{ $User->clark }}
</td>
@endforeach

回答1:


first please check the foreign and local key's are correct in the relation function implementation. after that try dumb the data like

dd($dataUser )

and check whether the user model's relations attributes actually contains the relationship model if its not empty you can access the property like

$User->concessionaire->property

if the relations attributes shows empty then you might have put incorrect local or foreign keys in the relationship implementation function.

you should follow

$this->hasOne(Relation::class, 'foreign key in related model', 'local key')



回答2:


function concessionaire()
 {
   return $this->hasOne( Concessionaire::class, 'user_id', 'id');
 }

Now you can access the property with

@foreach($dataUser as $User)
  <td>
    {{ $User->concessionaire->property }}
 </td>
@endforeach

Hope this helps



来源:https://stackoverflow.com/questions/49093987/display-in-view-of-one-to-one-relation-in-laravel-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!