在使用with方法时,是否有访问模型属性的方法



嘿,伙计们,我有问题。我试图通过定义一个范围来装载我的购物篮项目:

public function apply(Builder $builder, Model $model)
{
$builder->with(['product']);
}

我的产品关系篮模型如下:

public function product()
{
if ($this->used_product_id) {
return $this->belongsTo(UsedProduct::class, 'used_product_id', 'id');
} else {
return $this->belongsTo(Product::class, 'product_id', 'id');
}
}

但问题是当使用with(($this->used_product_id返回null,并且我无法访问我当前的模型属性。你有什么解决办法吗?

我会尝试这样的东西:

class Basket extends Model
{
public function newProduct()
{
return $this->belongsTo(Product::class, 'product_id', 'id');
}
public function usedProduct()
{
return $this->belongsTo(UsedProduct::class, 'used_product_id', 'id');
}
public function product()
{
return $this->usedProduct ?? $this->newProduct ?? null;
}
}

为了确保产品被急切地加载,你必须同时加载这两种产品,比如

Basket::with(['newProduct','usedProduct'])->get()

您可以将您的作用域定义为匿名全局作用域

class Basket extends Model
{
protected static function booted()
{
static::addGlobalScope('withProduct', function (Builder $builder) {
$builder->with('product');
});
}
public function product()
{
if ($this->used_product_id) {
return $this->belongsTo(UsedProduct::class, 'used_product_id', 'id');
} else {
return $this->belongsTo(Product::class, 'product_id', 'id');
}
}
}

或者使用$with属性。

class Basket extends Model
{
/**
* The relations to eager load on every query.
*
* @var array
*/
protected $with = ['product'];
public function product()
{
if ($this->used_product_id) {
return $this->belongsTo(UsedProduct::class, 'used_product_id', 'id');
} else {
return $this->belongsTo(Product::class, 'product_id', 'id');
}
}
}

最新更新