jeudi 26 novembre 2015

Laravel relation with 2 different models in same relation

I'm trying to do this in Laravel5: I have model order_item with attributes: order_item_id, item_id and item_type. Item_id is ID of related item. And item_type is "product" or "service". Order_item has function item() where I want to put relation with product or service in dependence on item_type. For example:

order_item: item_id = 1; item_type = 'product' => item() should return model App\Models\Product

if order_item is like this:

`order_item: item_id = 1; item_type = 'service' => item() should return model App\Models\Service`

Here is example of my model:

<?php namespace App\Models;

use App\Models\Model;

class OrderItem extends Model
{

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'orders_items';

    protected $primaryKey = 'order_item_id';

    /**
     * The attributes that are mass assignable.
     *
     *  item_type: product | service
     *
     * @var array
     */
    protected $fillable = ['order_item_id', 'order_id', 'item_id', 'item_type'];



    public function order() {
        return $this->hasOne('App\Models\Order', 'order_id', 'order_id');
    }

    public function item() {
    }

}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire