【发布时间】: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