从laravel中的两个独立模型获取数据
我想获取与id相关的数据,我使用从laravel中的两个独立模型获取数据,laravel,laravel-5,Laravel,Laravel 5,我想获取与id相关的数据,我使用find($id)方法来获取这些数据,现在我想从两个具有一对多关系的表中获取数据 如何从两个表中获取与相同id相关的数据 我试着这样做,但没有成功: public function show($id) { $post=Clients::find($id); return view('pet.shw',['post'=>$post,'pets'=>$post->pets]); } 为什么不使用with()我有简单的解决方案,但
find($id)
方法来获取这些数据,现在我想从两个具有一对多关系的表中获取数据
如何从两个表中获取与相同id相关的数据
我试着这样做,但没有成功:
public function show($id)
{
$post=Clients::find($id);
return view('pet.shw',['post'=>$post,'pets'=>$post->pets]);
}
为什么不使用
with()
我有简单的解决方案,但可能不是最好的解决方案:
Post::with('pets')->where('id',$id)->first()代码>
也许下面的代码是我不测试它的工作:
Post::with('pets')->查找($id)
当然,在Post
对象中应该有comments
方法:
public function pets(){
return $this->hasMany(Pet::class);
}
希望有帮助您需要首先定义客户
模型和宠物
模型之间的关系
因此,在App\Client
中,您将具有以下关系:
public function pets()
{
return $this->hasMany(Pet::class);
}
public function client()
{
return $this->belongsTo(Client::class)
}
在App\Pet
中,您将具有以下关系:
public function pets()
{
return $this->hasMany(Pet::class);
}
public function client()
{
return $this->belongsTo(Client::class)
}
然后,您应该能够在控制器中执行此操作:
public function show($id)
{
$post = Client::with('pets')->find($id);
return view('pet.shw')
->withPost($post);
}
并在pet.shw
视图中这样访问您的关系:
foreach($post->pets as $pet) {}
有关详细信息,请阅读这可能会对您有所帮助