gpt4 book ai didi

mysql - Laravel获取MySQL在Eloquent模型中查询Builder语句

转载 作者:行者123 更新时间:2023-11-29 17:27:21 24 4
gpt4 key购买 nike

给出下表:


+----+----------+------------+
|编号 |父 ID|名称 |
+----+----------+------------+
| 1 |空 |家长1|
| 2 | 1 | child 1|
| 3 | 1 | child 2|
| 4 | 1 | child 3|
| 5 |空 |家长2|
| 6 | 1 | child 4|
| 7 | 1 | child 5|
| 8 | 1 | child 6|
+----+----------+------------+

我想选择相同的数据,即使提供的 ID 是否为父项。因此,如果提供的 ID = 1(父级)或 ID = 3(子级),我想选择完全相同的数据:


+----+----------+------------+
|编号 |父 ID|名称 |
+----+----------+------------+
| 1 |空 |家长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;

希望这有帮助。

关于mysql - Laravel获取MySQL在Eloquent模型中查询Builder语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com