laravel sql select用户电子邮件谁列出了status=listed的房间

mfuanj7w  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(273)

我有两张table:


**users**

id | name | email | ...
-----------

**rooms**

user_id | title | status | ...
---------------------------

我如何才能选择所有用户的电子邮件与房间的房间状态列在拉维5?

amrnrhlw

amrnrhlw1#

如果您已经定义了 App\User 以及 App\Room 像这样的模特。

class User {
    /* other codes in your model goes here */
    public function rooms(){
        return $this->hasMany(App\Room::class);
    }
}

class Room {
    /* other codes in your model goes here */
    public function user(){
        return $this->belongsTo(App\User::class);
    }
}

您可以检索所有用户的电子邮件,其中的房间状态如下所示

$users= \App\User::with(['rooms' => function($query){
    $query->where('status', 'listed');
}])->pluck('email');
7gcisfzg

7gcisfzg2#

你要做的事,必须用“with”和“has”

$user = User::with(['room'])->whereHas('room,function($query){
            $q->where('status',1);

    })->get();

创建用户和房间的模型&用户名房间中的一种关系。上面的那个能解决你的问题吗

相关问题