Laravel parent/children relationship on it's own model

五迷三道 提交于 2019-12-12 13:33:47

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/31589746/laravel-parent-children-relationship-on-its-own-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!