【问题标题】:Laravel. Eloquent query拉拉维尔。雄辩的查询
【发布时间】:2015-06-30 10:14:32
【问题描述】:

我收到了这个查询:

$users = DB::table('users')->whereExists(function($query)
        {
            $query->select(DB::raw(1))
               ->from('galleries')
               ->whereRaw('galleries.user_id = users.id');
        })->get();

此查询选择所有拥有图库的用户。问题是我现在不能使用雄辩的关系。每当我尝试像这样循环时:

@foreach ($user->gallery as $gallery)
    {{$gallery->name}}      
@endforeach 

我得到错误:

Undefined property: stdClass::$gallery

所有其他表都会发生这种情况。我在这里做错了什么?我的关系已定义,它们工作得很好,我只在这个查询中遇到了问题。谢谢。

编辑
由于它不是 eloquent 查询,您能否向我展示如何将查询写入几个具有 eloquent 的表中的示例。例如,我需要在 example

中具有状态已批准的所有用户

【问题讨论】:

  • 您不是从User 模型中选择,而是从DB::table('users') 中选择。
  • 你这里没有使用 eloquent,你使用的是 fluent,2 个不同的东西。如果usersgaleries 处于关系中,则不需要这样做。
  • 谢谢。那么你能告诉我一个例子,我如何为 2 个表编写雄辩的查询吗?因为我只需要那些有画廊的用户?这只是一个例子,在实时项目中,我必须选择所有用户,其中画廊的状态已获得批准。
  • 请发布您的用户和图库模型代码
  • 我自己设法做到了。我使用了 User:: 而不是 DB::table('users')。感谢您的帮助。

标签: php mysql laravel eloquent


【解决方案1】:

首先,在 User 类中确定一个关系,像这样:

class User {
    // Determine relation to Example table
    public function examples() {
        return $this->hasMany('Example', 'user_id', 'id'); // second parameter is the foreign key
    }
}

然后查询:

User::whereHas('examples', function( $query ) {
    $query->where('status','approved');
})->get();

【讨论】:

    猜你喜欢
    • 2015-08-24
    • 2017-09-02
    • 2018-02-25
    • 1970-01-01
    • 2021-06-02
    • 2018-01-01
    • 2014-11-12
    • 2016-12-16
    • 2015-04-13
    相关资源
    最近更新 更多