【问题标题】:Laravel parent/children relationship on it's own modelLaravel 自己模型上的父/子关系
【发布时间】:2015-10-13 21:35:12
【问题描述】:

我想获取所有至少有一个孩子的优惠券,一张优惠券可以有多个优惠券孩子,但任何优惠券只能有一个父母。

我用以下模型和调用设置它,它生成的查询是所需的,直到这部分:'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');
    }
}

【问题讨论】:

  • 我以前在模型上使用过这种父子方法。你有什么问题?
  • 它什么也不返回。即使我将 Laravel 生成的查询直接在数据库上运行。
  • 由于这部​​分and 'vouchers'.'parent_id' = 'vouchers'.'id'——它在那个子查询中引用了自己。外部查询需要vouchers 上的别名。
  • 您可以使用数据透视表吗?
  • 此问题已在 5.0 github.com/laravel/framework/pull/8193 中报告并修复,遗憾的是版本 4 没有后端端口。

标签: php laravel laravel-4 relationship


【解决方案1】:

此问题已在 5.0 https://github.com/laravel/framework/pull/8193 中报告并修复

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

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

请注意,修改框架的代码库存在风险,但 Laravel 4.x 版本将不再修复错误,仅会再进行几个月的安全修复。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-05
    • 2020-12-19
    • 2018-01-28
    • 1970-01-01
    • 2016-04-17
    • 2014-08-27
    相关资源
    最近更新 更多