给定下表:
+----+----------+------------+
| 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 = 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' );
}
这是关系的完美用例:
public function parent() {
$this->belongsTo(self::class, 'parent_id');
}
public function children() {
$this->hasMany(self::class, 'parent_id');
}
$parent = Model::with('children')->find(1); // with eager loading
$parent->children;
希望这有帮助。