【问题标题】:Laravel get MySQL to query Builder statement in Eloquent modelLaravel 让 MySQL 在 Eloquent 模型中查询 Builder 语句
【发布时间】: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


    【解决方案1】:

    这是关系的完美用例:

    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;
    

    希望这会有所帮助。

    【讨论】:

    • 我可能会更新答案以加载父母以及孩子。
    • 抱歉,我没有向您展示具有 parent()childs() 函数的其余代码正是这样做的。但我总是希望父母也包括孩子的兄弟姐妹。这就是为什么我把这个丑陋的解决方案贴在上面。 ;-)
    猜你喜欢
    • 1970-01-01
    • 2020-10-30
    • 2021-07-07
    • 2017-06-02
    • 1970-01-01
    • 2021-08-19
    • 2016-06-21
    • 2016-07-25
    • 2016-09-30
    相关资源
    最近更新 更多