简体   繁体   中英

Laravel Relationship Composite Primary Key

How to define relationship in Laravel using composite keys?

I have 2 tables which have 2 primary keys, order [id_order, id_trip] and detail order [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)

I think I have a mistake in defining relationship in model. Here's my code:

Order.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

<?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

     @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 . You hit "Array to string conversion" error becouse Laravel try to cast array to string.

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

You can't. Eloquent doesn't support composite primary keys. But you can do using an open-source package called LaravelTreats .

Hope this helps you

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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