【问题标题】:Eloquent custom relationship hasMany (foreign field contains text concatenated by foreign key)Eloquent 自定义关系 hasMany(外域包含由外键连接的文本)
【发布时间】:2020-11-27 11:28:27
【问题描述】:

我有这个数据库结构。 2 个表:shipment_outstock_move

shipment_out 具有典型的主键整数 id 字段。

stock_move 有一个名为shipment 的字段,它是字符串类型。该字段可以具有以下值:

"stock_shipment_out,1512",
"stock_shipment_in,65400",
"sale.line,358",
(...)

问题是表stock_move与基于同一字段的多个表相关,所以它之前有这个文本。

在这种情况下,我想定义关系:shipment_out hasMany stock_move。 所以我需要通过 stock_move.shipment 加入,有这个值:'stock_shipment_out,{id}'。

那么我该如何定义这种关系呢?会是这样的:

public function stockMoves()
{
    return $this->hasMany(StockMove::class, 'shipment', 'stock.shipment.out,id');
}

我可以通过查询生成器实现这种关系:

    $shipments = ShipmentOut
        ::join('public.stock_move', DB::raw('CONCAT(\'stock.shipment.out,\',public.stock_shipment_out.id)'), '=', 'stock_move.shipment')
        ->where('stock_shipment_out.id', '=', $shipmentOut);

但我也需要一段感情……

【问题讨论】:

    标签: laravel eloquent foreign-keys relationship


    【解决方案1】:

    为了解决这个问题,我必须定义一个自定义属性,然后我可以定义与这个字段的关系。

    public function getStockMoveShipmentAttribute()
    {
        return "stock.shipment.out,{$this->id}";
    }
    
    public function stockMoves()
    {
        return $this->hasMany(StockMove::class, 'shipment', 'stock_move_shipment')
    }
    

    现在我可以使用这种关系,但它只是一个方向...... 如果我想定义与逆相同的关系,它不起作用。

    我打开了另一个问题来解释它:Laravel relationship based on custom attribute not working both directions

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-06
      • 1970-01-01
      • 2021-12-12
      • 2019-08-12
      相关资源
      最近更新 更多