Laravel parent / child relationship on its own model

I would like to receive all vouchers that have at least one child, a voucher can have multiple voucher children, but any voucher can only have one parent.

I have set it up with the following models and calls, and the request it generates as desired, for now this part: 'vouchers'.'parent_id' = 'vouchers'.'id'

Required functionality:

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



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


Result 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



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');



source to share

1 answer

This issue was posted and fixed in 5.0

Unfortunately, there is no return port for version 4.

However, if you'd like to apply the fix yourself, you can see the changelog here:

Be careful, the framework change is under threat, but there will be no more bug fixes in Laravel 4.x, just security fixes for a few more months.



All Articles