Laravel 雄辩的查询和刀片显示
我有我的users表和一个带有用户id的profile表 在我的Laravel 雄辩的查询和刀片显示,laravel,eloquent,Laravel,Eloquent,我有我的users表和一个带有用户id的profile表 在我的用户型号中,我有 public function profiles() { 返回$this->belongsTo('App\Models\Profile'); } 而在我的配置文件中则相反 对于要在配置文件页面上显示的功能,我有 $profiles=Profile::get() ->其中('users','user_id','=','profile.user_id'); 返回视图('profile.profile')->带有('p
用户
型号中,我有
public function profiles()
{
返回$this->belongsTo('App\Models\Profile');
}
而在我的配置文件中则相反
对于要在配置文件页面上显示的功能,我有
$profiles=Profile::get()
->其中('users','user_id','=','profile.user_id');
返回视图('profile.profile')->带有('profiles',$profile');
但我不确定这是否正确。努力保持口才。我也不知道如何在我的个人资料页面上显示来自用户和个人资料表的信息。有人能帮忙吗?可能就这么简单:
$profiles = $user->profiles;
return view('profile')->with('profiles', $profiles);
只要遵循正常的laravel命名约定,这意味着用户表被称为users
,并且主键为id
,这是自动递增的。profiles表名为profiles
,它有一个名为user\u id
的FK
如果没有,您可能需要:
public function profiles()
{
return $this->hasMany("App\Profile", "user_id");
}
您是否尝试过使用join()
?是的,当我添加($profiles)时它会收集,但不确定如何在刀片服务器上显示。例如,名称在用户表上,但地址在刀片服务器文件的配置表上。您可以使用@foreach($profiles as$profile){{$profile->key}@endforeach
您使用的语法是一个join()
,而不是一个where()
,但是在通过get()
执行查询之后,您将链接它。。。您的代码应该是Profile::where('user_id',$someId)->first()
(如果需要1条记录,或者->get()
(如果需要多条记录),或者只需user::find($someUserId)->profiles
。。。我越是看这个问题,我就越觉得不对profiles()
表示很多(因为它是复数),但是belongsTo()
只返回一条记录或null
…应该是$profiles=$user->profiles()->get()
或$profiles=$user->profiles
@IGP-您当然是正确的。如果不能够运行代码,那么编写代码是非常困难的。如果使用$user->profiles()
,您的代码实际上会运行得很好,但它不会做太多:P您有一个未执行的查询,它仍然有效。容易忽视的事情:)