【问题标题】:Nested query with Eloquent使用 Eloquent 进行嵌套查询
【发布时间】:2013-08-08 04:18:53
【问题描述】:

我的 Location 模型中有这种关系:

public function special_users() {
    return $this->users()
    ->where('type_id', '=', '2')
    ->orWhere('type_id', '=', 'null');
}

但我想要的是 type_id = 2 的用户和 type_id = null 的用户,前提是该位置没有 type_id = 2 的用户。

这可能吗?

【问题讨论】:

  • 仍在寻找解决方案。 . .

标签: laravel laravel-4 eloquent


【解决方案1】:

我设计了一个解决方案。所以对于任何有类似问题的人来说,这里就是。我确信它可以以更低的成本执行,并且很想展示它是如何执行的,但现在,享受吧。

class Location extends Eloquent {
    protected $table = 'locations';

    public function users() {
        return $this->belongsToMany('User')->withTimestamps()->withPivot(['type_id']);
    }

    public function chef_users() {
        return $this->users()->where('type_id', '2');
    }
}

class DishController extends BaseController {
    $chef_locations = Location::with('chef_users')->get();
    foreach ($chef_locations as $cl) {
        foreach ($cl->chef_users as $cu) {
            $chef_user_ids[] = $cu->id;
        }
    }

    $locations = Location::with(
        array('users' => function($lu_query) use($chef_user_ids) {
            $lu_query->where('type_id', '2');
            $lu_query->orWhere(function($nested_query) use($chef_user_ids) {
                $nested_query->whereNull('type_id');
                $nested_query->whereNotIn('user_id', $chef_user_ids);
            });
        })
    )
}

【讨论】:

    【解决方案2】:

    您的问题是关于 DBMS 的;与 Laravel 无关。

    通常这些类型的查询是通过查询 type_id = 2 来执行的。如果没有找到记录,只需在您获取 type_id = 0 的地方触发第二个查询。

    【讨论】:

    • 谢谢 R。您的建议不起作用,因为会找到 type_id = 2 的用户的记录。我需要找到 type_id = 0 (null) 的用户,前提是该特定用户没有找到 type_id = 2 的。我确定这是因为我没有正确解释问题。不用担心,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-06-27
    • 1970-01-01
    • 1970-01-01
    • 2014-09-27
    • 2019-03-15
    • 2017-04-13
    • 1970-01-01
    • 2015-09-01
    相关资源
    最近更新 更多