简体   繁体   English

Laravel 关系复合主键

[英]Laravel Relationship Composite Primary Key

How to define relationship in Laravel using composite keys?如何使用复合键定义 Laravel 中的关系?

I have 2 tables which have 2 primary keys, order [id_order, id_trip] and detail order [id_trip, id_seat].我有 2 个表,它们有 2 个主键,订单 [id_order, id_trip] 和详细订单 [id_trip, id_seat]。

I tried to get $order->detail_order->id_seat in index.blade.php, but the error is Array to string conversion (View: D:\xampp\htdocs\travel\resources\views\order\index.blade.php)我试图在 index.blade.php 中获取 $order->detail_order->id_seat,但错误是数组到字符串的转换(查看:D:\xampp\htdocs\travel\resources\views\order\index.blade.php )

I think I have a mistake in defining relationship in model.我想我在 model 中定义关系时犯了一个错误。 Here's my code:这是我的代码:

Order.php订购.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\CompositeKeyTrait;

class Order extends Model{

    use CompositeKeyTrait;
    protected $table = "order";
    protected $fillable = [
        'id_order',
        'id_trip', 
        'id_users_customer', 
        'date_order',
        'id_users_operator'
    ];

    protected $primaryKey = ['id_order', 'id_trip'];

    public function detail_order(){   
        return $this->hasMany(Detail_Order::class);   
    }
}

Detail_Order.php Detail_Order.php

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\CompositeKeyTrait;

class Detail_Order extends Model{
    use CompositeKeyTrait;

    protected $table = "detail_order";
    protected $fillable = [
        'id_trip',  
        'id_seat',
        'id_users_feeder', 
        'id_order',
        etc
    ];

    protected $primaryKey = ['id_trip', 'id_seat'];

    public function order(){
        return $this->belongsTo(Order::class, 'id_order', 'id_trip');
    }
}

index.blade.php index.blade.php

     @foreach($order as $o)
        <tr>
            <td>{{ $o->detail_order->id_seat }}</td>
        </tr>
     @endforeach

Does anyone have any idea?有人有什么主意吗? Thanks.谢谢。

Laravel does not support Composite Primary Key . Laravel 不支持复合主键 You hit "Array to string conversion" error becouse Laravel try to cast array to string.您遇到“数组到字符串转换”错误,因为 Laravel 尝试将数组转换为字符串。

protected $primaryKey = ['id_order', 'id_trip'];

You can't.你不能。 Eloquent doesn't support composite primary keys. Eloquent 不支持复合主键。 But you can do using an open-source package called LaravelTreats .但是您可以使用名为LaravelTreats 的开源 package

Hope this helps you希望这可以帮助你

Ref: https://stackoverflow.com/a/36995763/10765839参考: https://stackoverflow.com/a/36995763/10765839

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM