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
您有三个选择:
$with
在模型中使用
class Product extends Model
{
protected $with = ['ingredients'];
public function ingredients()
{
return $this->belongsToMany(Ingredient::class)->withPivot('value');
}
}
Run Code Online (Sandbox Code Playgroud)加载关系并返回产品:
public function get(Product $product)
{
$product->ingredients;
return $product;
}
Run Code Online (Sandbox Code Playgroud)load
在产品上使用方法:
public function get(Product $product)
{
return $product->load('ingredients');
}
Run Code Online (Sandbox Code Playgroud) 归档时间: |
|
查看次数: |
1465 次 |
最近记录: |