Laravel polymorphic relationships return null

1.6k Views Asked by At

I'm trying to join an Order and 2 different OrderDetailType tables.

OrderDetailType1
    - id
    - order_id

OrderDetailType2
    - id
    - order_id

Order
    - id
    - detail_type    'type1' or 'type2'

And I have followed Polymorphic Relations example in official Laravel site and adapted to my code like:

class OrderDetailType1 extends Model {

    public function order() {
        return $this->morphOne('App\Order', 'type_detail');
    }

}

class OrderDetailType2 extends Model {

    public function order() {
        return $this->morphOne('App\Order', 'type_detail');
    }

}

class Order extends Model {

    public function type_detail() {
        return $this->morphTo();
    }

}

And I have put Relation::morphMap() into boot() function in AppServiceProvider class already.

use Illuminate\Database\Eloquent\Relations\Relation;

class AppServiceProvider extends ServiceProvider {

    public function boot() {
        Relation::morphMap([
            'type1' => 'App\OrderDetailType1',
            'type2' => 'App\OrderDetailType2'
        ]);
    }
}

The example is different from my code. The difference is both foreign key and the attribute that specifying which table to be joined should be in Order. So I cannot use morphTo() and morphOne() like the example to solve this.

I am confuse which classes should contain morphTo() and morphOne(). And is there any overload to specify which table have foreign key and type?

I use Laravel 5.4. Thank You in Advance.

1

There are 1 best solutions below

1
Jonas Staudenmeir On

The _id column has to be in the Order table:

OrderDetailType1
    - id

OrderDetailType2
    - id

Order
    - id
    - detail_type
    - detail_id

class OrderDetailType1 extends Model {

    public function order() {
        return $this->morphOne('App\Order', 'detail');
    }

}

class OrderDetailType2 extends Model {

    public function order() {
        return $this->morphOne('App\Order', 'detail');
    }

}

class Order extends Model {

    public function detail() {
        return $this->morphTo();
    }

}