laravel 能说会道与垃圾桶

lmvvr0a8  于 2023-03-24  发布在  其他
关注(0)|答案(2)|浏览(130)

我有一组具有以下关系的产品模型:

  • 订购产品-〉帐户产品-〉产品 *

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返回HasOneThrough关系?

ig9co6j1

ig9co6j11#

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');
    }
}
lymnna71

lymnna712#

return $this->hasOneThrough(...)
            ->withTrashed()
            ->withTrashedParents();

相关问题