【问题标题】:Nested Eloquent Relation - HasOneThrough Issue嵌套的 Eloquent 关系 - HasOneThrough 问题
【发布时间】:2021-03-10 00:43:03
【问题描述】:

我有以下表格设置:

Product_variant

Product_variant -> id, name, code, image

Warehouse

Warehouse -> id, name, address

Product Variant Stock

Product_Variant_stock -> stock_id, warehouse_id, variant_id, stock_qty

现在,当我尝试访问产品变体信息时,我需要获取有关变体存储在哪个仓库中的信息。

我在 ProductVariation 模型中的尝试:

public function warehouseName()
{
    return $this->hasOneThrough(Warehouse::class, ProductVariantStock::class, 'warehouse_id', 'id');
}

上面没有按预期工作。任何帮助表示赞赏。

【问题讨论】:

    标签: eloquent laravel-7 eloquent-relationship


    【解决方案1】:

    laravel hasOneThrough 像这样工作

    class ModelA extends Model
    {
        ...
        
        public function cModel()
        {
            return $this->hasOneThrough(
                ModelC::class,
                ModelB::class,
                'model_a_id', // Key on B that relates to A
                'model_c_id', // Key on C that relates to B
                'a_id',       // Key on A that relates to B
                'b_id',       // Key on B that relates to C
            );
        }
    }
    

    所以你的代码将是

    public function warehouseName()
    {
        return $this->hasOneThrough(Warehouse::class, ProductVariantStock::class, 'variant_id', 'id', 'id', 'warehouse_id');
    }
    

    【讨论】:

    • 有了这个,我收到消息:“SQLSTATE[42S22]: Column not found: 1054 Unknown column 'warehouses.warehouse_id' in 'on Clause' (SQL: select warehouses.*, @ 987654324@.variant_id 作为laravel_through_keywarehouses 内部连接product_variation_stocksproduct_variation_stocks.stock_id = warehouses.warehouse_id 其中product_variation_stocks.@1 限制)。然后我把warehouse_id改成id然后就没有记录了
    • nope.. 它像这样工作 return $this->hasOneThrough(Warehouse::class, ProductVariationStock::class, 'variant_id', 'id', 'id', 'warehouse_id');
    • 有时,处理这些雄辩的复杂关系很有趣 :).. 干杯
    • 是的。如果我们了解这些,那真的很有趣。
    • 正如您所解释的那样,Laravel 文档中并没有那么清楚,我们做到了。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    • 2019-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多