如何在某种条件下显示来自另一个模型的数据?



我有PostAd模型和PostImage模型。 他们有一对多的关系。 一个帖子广告有很多帖子图像。

现在我想在主图像 == 1 的情况下显示来自 PostImage 的 PostAd 图像。

PostAd model
public function postimage()
{
return $this->hasMany(PostImage::class,'postad_id');
}
Controller of PostAd
$data['userads']  =  PostAd::with('postimage')->where('user_id',$id)->paginate(4);
i want to display in blade file
<td class="invert-image"><img src="{{asset('advertisementimage/'.$user->postimage->image)}}" alt="Images" class="img-responsive" style="width:50px;" /></td>

我想通过在另一个模型中应用条件来显示。 但是向我展示了一个错误。 此集合实例上不存在属性图像。

在您的控制器中使用它,以便您可以获得有图像的帖子

$data['userads']  =  PostAd::whereHas('postimage')->where('user_id',$id)->paginate(4);

因为你们的关系实际上是返回多个PostImage。因此,您必须遍历$user->postimage才能访问image属性。

$data['userads']  =  PostAd::with(['postimage' => function ($query){
$query->whereNotNull('image');
}])->where('user_id',$id)->paginate(4);

您可以通过这种方式将条件应用于关系。

我终于找到了答案。 我只是在模型中应用了条件。

public function postimage()
{
return $this->hasMany(PostImage::class,'postad_id')->where('mainimage',1);
}

最新更新