Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从laravel中的两个独立模型获取数据_Laravel_Laravel 5 - Fatal编程技术网

从laravel中的两个独立模型获取数据

从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()我有简单的解决方案,但

我想获取与id相关的数据,我使用
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) {} 
有关详细信息,请阅读

这可能会对您有所帮助