Laravel自己的模型上的父母/孩子关系 [英] 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.
我使用以下模型和调用对其进行设置,并根据需要生成查询,直到这一部分为止:'vouchers'.'parent_id' = 'vouchers'.'id'
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'
想要的功能:
$vouchers = Voucher::has('children')->get();
或
$vouchers = Voucher::has('parent')->get();
结果查询
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');
}
}
推荐答案
This issue has been reported and fixed in 5.0 https://github.com/laravel/framework/pull/8193
不幸的是,版本4没有后端口.
Unfortunately there is no back port for the version 4.
但是,如果您想自己应用此修复程序,则可以在此处查看修改列表: https://github.com/laravel/framework/pull/8193/files
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
请注意,修改框架的代码库存在风险,但是Laravel 4.x版本将不再有错误修复,只有几个月的安全修复.
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.
这篇关于Laravel自己的模型上的父母/孩子关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!