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

时间:2018-11-01 15:00:00

标签: laravel laravel-5

我想获取与id相关的数据,我使用了find($id)方法来获取这些数据,现在我想从具有一对多关系的两个表中获取数据。

如何从两个表中获取与相同ID相关的数据?

我尝试过这种方式,但是没有用:

public function show($id)
{

    $post=Clients::find($id);

    return view('pet.shw',['post'=>$post,'pets'=>$post->pets]);
}

2 个答案:

答案 0 :(得分:1)

为什么不使用with(),我有一个简单的解决方案,但可能不是最好的解决方案: Post::with('pets')->where('id',$id)->first();

也许下面的代码是我不对其进行测试的工作:

Post::with('pets')->find($id);

当然,您的comments对象中应该有Post方法:

 public function pets(){

   return $this->hasMany(Pet::class);
}

希望帮助

答案 1 :(得分:0)

您需要首先定义Client模型和Pet模型之间的关系

因此,在App\Client中,您将具有以下关系:

public function pets()
{
    return $this->hasMany(Pet::class); 
}

App\Pet中,您将具有以下关系:

public function client()
{
    return $this->belongsTo(Client::class)
}

然后您应该可以在Controller中执行此操作:

public function show($id)
{
    $post = Client::with('pets')->find($id);

    return view('pet.shw')
        ->withPost($post);
}

,并在pet.shw视图中访问您的关系,

foreach($post->pets as $pet) {} 

有关Eloquent Relationships的更多信息

相关问题