Eloquent hasOneThrough withTrashed
Eloquent hasOneThrough withTrashed
我有一组具有以下关系的产品模型:
OrderProduct -> AccountProduct -> Product
OrderProduct 模型属于 AccountProduct,并且与产品有 hasOneThrough
关系。
这些关系工作正常,直到我处于 accountProduct 和 Product 已被软删除的情况。我仍然可以通过链接检索关系,但 hasOneThrough
在这种情况下无法工作。
public function accountProduct(): BelongsTo
{
return $this->belongsTo(AccountProduct::class)
->withTrashed();
}
public function product(): HasOneThrough
{
return $this->hasOneThrough(
Product::class,
AccountProduct::class,
'id',
'id',
'account_product_id',
'product_id'
)->withTrashed();
}
输出:
echo $orderProduct->accountProduct->product->id
"1"
echo $orderProduct->product
"Trying to get property ID of a non object"
当 accountProduct 和 orderProduct 都被软删除时,我是否可以更改代码以将 Eloquent 变为 return HasOneThrough 关系?
Laravel 对此没有原生支持。
我已经为它创建了一个包:https://github.com/staudenmeir/eloquent-has-many-deep
class OrderProduct extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function product(): HasOneThrough
{
return $this->hasOneDeep(
Product::class,
[AccountProduct::class],
['id', 'id'],
['account_product_id', 'product_id']
)->withTrashed()
->withTrashed('account_products.deleted_at');
}
}
我有一组具有以下关系的产品模型:
OrderProduct -> AccountProduct -> Product
OrderProduct 模型属于 AccountProduct,并且与产品有 hasOneThrough
关系。
这些关系工作正常,直到我处于 accountProduct 和 Product 已被软删除的情况。我仍然可以通过链接检索关系,但 hasOneThrough
在这种情况下无法工作。
public function accountProduct(): BelongsTo
{
return $this->belongsTo(AccountProduct::class)
->withTrashed();
}
public function product(): HasOneThrough
{
return $this->hasOneThrough(
Product::class,
AccountProduct::class,
'id',
'id',
'account_product_id',
'product_id'
)->withTrashed();
}
输出:
echo $orderProduct->accountProduct->product->id
"1"
echo $orderProduct->product
"Trying to get property ID of a non object"
当 accountProduct 和 orderProduct 都被软删除时,我是否可以更改代码以将 Eloquent 变为 return HasOneThrough 关系?
Laravel 对此没有原生支持。
我已经为它创建了一个包:https://github.com/staudenmeir/eloquent-has-many-deep
class OrderProduct extends Model
{
use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
public function product(): HasOneThrough
{
return $this->hasOneDeep(
Product::class,
[AccountProduct::class],
['id', 'id'],
['account_product_id', 'product_id']
)->withTrashed()
->withTrashed('account_products.deleted_at');
}
}