Laravel父母/子女关系就是它自己的模特

时间:2015-07-23 14:04:28

标签: php laravel laravel-4 relationship

我希望获得至少有一个孩子的所有优惠券,优惠券可以有多个优惠券儿童,但任何优惠券只能有一个亲子。

我使用以下模型和调用进行设置,并根据需要生成查询,直到此部分:'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');
    }
}

1 个答案:

答案 0 :(得分:1)

此问题已在5.0 https://github.com/laravel/framework/pull/8193

中报告并修复

不幸的是版本4没有后端口。

但是,如果您想自己应用此修复程序,可以在此处查看修改列表:https://github.com/laravel/framework/pull/8193/files

小心,修改框架的代码库存在风险,但Laravel 4.x版本上不再有bug修复,只有几个月的安全修复。

相关问题