Nicklas Kevin Frank
Nicklas Kevin Frank

Reputation: 6337

Laravel parent/children relationship on it's own model

I want to get all the vouchers that have at least one child, a voucher can have multiple voucher children, but any voucher can only have one parent.

I set it up with the following models and calls, and the query it generates is as desired, until this part: 'vouchers'.'parent_id' = 'vouchers'.'id'

Wanted functionality:

$vouchers = Voucher::has('children')->get();

or

$vouchers = Voucher::has('parent')->get();

Resulted Query

select * from `vouchers` where `vouchers`.`deleted_at` is null 
and (select count(*) from `vouchers` where `vouchers`.`deleted_at` is null 
and `vouchers`.`parent_id` = `vouchers`.`id` 
and `vouchers`.`deleted_at` is null ) >= 1

Models:

class Voucher extends baseModel {

    public function parent()
    {
        return $this->belongsTo('Voucher', 'parent_id');
        // return $this->belongsTo('Voucher', 'parent_id', 'id'); <- attempted but din't work
    }

    public function children()
    {
        return $this->hasMany('Voucher', 'parent_id');
    }
}

Upvotes: 3

Views: 2619

Answers (1)

Needpoule
Needpoule

Reputation: 4576

This issue has been reported and fixed in 5.0 https://github.com/laravel/framework/pull/8193

Unfortunately there is no back port for the version 4.

However if you want to apply the fix yourself you can see the list of modifications here : https://github.com/laravel/framework/pull/8193/files

Be carefull, modifying the framework's code base is at risk but there will be no more bug fixes on Laravel 4.x version, only security fixes for a few more month.

Upvotes: 1

Related Questions