我遇到了完全相同的问题,让我告诉你我是如何解决的。
在我的例子中,materials 和 customer_types 之间存在belongsToMany 关系,数据透视表包含特定客户类型的材料价格,因此数据透视表中的记录(价格)与customer_types 一样多。
我的预期:当请求特定 customer_type 的价格时,我希望获得该特定 customer_type 的范围价格作为嵌套元素。
我得到了什么:只有 1 个元素的集合。
这是我一开始在我的模型中所拥有的:
class Material extends Model
{
public function customer_types(){
return $this->belongsToMany('App\CustomerType', 'customertype_material', 'material_id', 'customertype_id')->withPivot('price');
}
}
当然,当我为特定的 customer_type 请求 customer_types 时,结果不是预期的:
$resources = Material::with(['customer_types' => function($query) use ($customer_type_id){
$query->where('customertype_id', $customer_type_id);
}])->get();
它返回了一个带有 customer_types 嵌套集合的 Material 模型,上面有 1 个元素,迫使我使用 first() 或循环 1 个元素。
解决方案:创建一个扩展数据透视表的模型并向其添加关系。
创建了一个扩展枢轴的新模型:
use Illuminate\Database\Eloquent\Relations\Pivot;
class CustomertypeMaterial extends Pivot
{
protected $table = 'customertype_material';
protected $fillable = ['price', 'customertype_id', 'material_id'];
}
现在,在我的 Material Model 中添加了一个指向这个新模型的关系:
public function scoped_price(){
return $this->belongsTo('App\CustomertypeMaterial', 'id','material_id');
}
最后加载这个新关系的查询:
$resources = Material::with(['scoped_price' => function($query) use ($customer_type_id){
$query->where('customertype_id', $customer_type_id);
}])->get();
结果是一个 Material 模型,其中嵌套了一个 scoped_price 元素并由 customer_type_id 过滤
我不确定这是否是正确的方法,但它对我有用。
希望对你有帮助!