我怎样才能在morphTo关系中使用whereHas?

时间:2018-04-07 13:38:58

标签: laravel laravel-5 polymorphism laravel-eloquent laravel-5.6

我的产品型号如下:

<?php
...
class Product extends Model
{
    ...
    protected  $fillable = ['name','photo','description',...];
    public function favorites(){
        return $this->morphMany(Favorite::class, 'favoritable');
    }
}

我最喜欢的模特:

<?php
...
class Favorite extends Model
{
    ...
    protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
    public function favoritable()
    {
        return $this->morphTo();
    }
}

我的laravel雄辩地说:

$q = $param['q'];

$query = Favorite->where('user_id', auth()->user()->id)
                 ->with('favoritable');

if($q) {
    $query->whereHas('favoritable', function ($query) use ($q) {
        $query->where('name', 'like', "%$q%");
    });
}

$query = $query->paginate(5);

return $query

如果脚本已执行,则会出现如下错误:

  

未知栏&#39;名称&#39;

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:3)

<强>解决

我添加了这个方法:

public function product()
{
    return $this->belongsTo(Product::class, 'favoritable_id')
        ->where('favorites.favoritable_type', Product::class);
}

最喜欢的模特

我将laravel雄辩改变成这样:

$query->whereHas('product', function ($query) use ($q) {
    $query->where('name', 'like', "%$q%");
});

它有效

答案 1 :(得分:0)

答案 2 :(得分:0)

Laravel 5.8包括用于查询多态关系的新功能。

whereHasMorph()使得查询类似以下内容的多态关系成为可能:

Comment::whereHasMorph('commentable', [Post::class, Video::class], function 
($query) {
    $query->where('title', 'foo');
})->get();

哪个会产生类似以下查询的内容:

select * from "comments"
where (
  (
    "commentable_type" = 'App\Post' and exists (
      select * from "posts" where "comments"."commentable_id" = "posts"."id" and "title" = 'foo'
    )
  ) or (
    "commentable_type" = 'App\Video' and exists (
      select * from "videos" where "comments"."commentable_id" = "videos"."id" and "title" = 'foo'
    )
  )
)