【问题标题】:how to Querying Morph To Relationships如何查询变形到关系
【发布时间】:2021-08-17 03:52:18
【问题描述】:

尝试借助文档在 laravel 8 中查询 Polymorphic,但它显示错误

BadMethodCallException: Call to undefined method App\Models\Product::keywordable()

这是我的模型

关键字.php

public function products()
    {
        return $this->morphedByMany(Product::class, 'keywordable');
    }

产品.php

 public function keywords()
    {
        return $this->morphToMany(Keyword::class, 'keywordable');
    }

查询

$products = Product::whereHasMorph(
                    'keywordable',
                    [Keyword::class],
                    function (Builder $query) use ($request) {
                        $query->where('slug',  $request->keyword);
                    }
                )->get();

【问题讨论】:

    标签: laravel laravel-8 laravel-query-builder


    【解决方案1】:

    Keywordable 与您的产品模型无关。 您可以使用whereHasmethod 按关键字搜索

    使用 whereHas 方法

        $products = Product::wherHas( 'keywords', function ($query) use ($request) {
            $query->where('slug',  $request->keyword);
        })->get();
    

    如果您有其他关系,请使用 whereHasMorph

        $products = Product::wherHasMorph( 'keywords', [Keyword::class], function ($query) use ($request) {
            $query->where('slug',  $request->keyword);
        })->get();
    

    【讨论】:

      猜你喜欢
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-22
      • 2017-08-28
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      相关资源
      最近更新 更多