问题
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