Laravel - 返回控制器中参数的相关模型

mar*_*nar 0 routes laravel eloquent

我有以下路线:

Route::get('/api/products/{product}', 'ProductController@get');
Run Code Online (Sandbox Code Playgroud)

我的产品模型如下所示:

class Product extends Model
{
    public function ingredients()
    {
        return $this->belongsToMany(Ingredient::class)->withPivot('value');
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的控制器中,方法是:

public function get(Product $product)
{
    return $product;
}
Run Code Online (Sandbox Code Playgroud)

Product这仅以JSON 形式返回对象的属性。我还想返回相关成分和数据透视表值(就像使用该with方法一样),以及可能的其他相关模型。

return $product->with('ingredients')创建所有产品的集合,因此这实际上不起作用,我必须通过产品 ID 再次过滤它。显然,我可以自己构建 JSON,但如果我想要包含多个相关模型,这就变得很乏味。有没有一种简单的方法可以实现这一点?

小智 7

您有三个选择:

  1. $with在模型中使用

    class Product extends Model
    {
        protected $with = ['ingredients'];
        public function ingredients()
        {
            return $this->belongsToMany(Ingredient::class)->withPivot('value');
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  2. 加载关系并返回产品:

    public function get(Product $product)
    {
        $product->ingredients;
        return $product;
    }
    
    Run Code Online (Sandbox Code Playgroud)
  3. load在产品上使用方法:

    public function get(Product $product) 
    {
        return $product->load('ingredients'); 
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 我想这会起作用的。为了简单一点,我们也可以在控制器中这样写: public function get(Product $product) { return $product->load('ingredients'); } (2认同)