【发布时间】:2018-11-25 22:22:03
【问题描述】:
给定下表:
+----+----------+------------+
| id | parent_id| Name |
+----+----------+------------+
| 1 | NULL | Parent 1|
| 2 | 1 | Child 1|
| 3 | 1 | Child 2|
| 4 | 1 | Child 3|
| 5 | NULL | Parent 2|
| 6 | 1 | Child 4|
| 7 | 1 | Child 5|
| 8 | 1 | Child 6|
+----+----------+------------+
我想选择相同的数据,即使提供的 ID 是否为父 ID。 所以提供的 ID = 1(父)或者如果 ID = 3(子)我想选择这个完全相同的数据:
+----+----------+------------+
| id | parent_id| Name |
+----+----------+------------+
| 1 | NULL | Parent 1|
| 2 | 1 | Child 1|
| 3 | 1 | Child 2|
| 4 | 1 | Child 3|
+----+----------+------------+
我有一个有效的 MySQL 查询:
SELECT * FROM packages
WHERE id = 3
OR parent_id = 3
OR parent_id = (SELECT parent_id FROM packages WHERE id = 3)
OR id = (SELECT parent_id FROM packages WHERE id = 3)
因此,如果您将 3 替换为 1,您将获得与预期相同的结果。
我的包模型中已经有以下功能:
<?php
public function related()
{
$childParent = Package::select( 'parent_id' )->where( 'id', $this->id )->first();
$query = $this->where( 'id', $this->id )
->orWhere( 'parent_id', $this->id );
if ( null !== $childParent->parent_id ) {
$query
->orWhere( 'parent_id', $childParent->parent_id )
->orWhere( 'id', $childParent->parent_id );
}
return $query;
}
但这感觉……嗯……丑陋。我来自 Symfony,在这里可以使用 ORM 查询构建器轻松构建(并且使用很少的代码行)。
我是否缺少 Laravel Eloquent 中的一个功能来使它变得又好又短?
编辑:我已经有了这些功能,它们在不选择其他孩子和最终父母方面都不足:
<?php
public function parent()
{
return $this->belongsTo( Package::class, 'parent_id' )->withTrashed();
}
public function childs()
{
return $this->hasMany( Package::class, 'parent_id' );
}
【问题讨论】:
标签: mysql laravel laravel-5 model eloquent