簡體   English   中英

如何在 morphTo 關系 laravel 中使用 whereHas?

[英]How can I use whereHas in the morphTo relation laravel?

我的產品型號是這樣的:

<?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

如果腳本執行,則存在如下錯誤:

未知列“名稱”

我怎么解決這個問題?

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'
    )
  )
)

解決了

我添加了這個方法:

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

在最喜歡的模型中

我把 laravel eloquent 改成這樣:

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

有用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM