Laravel select * where id =(select id )

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45934017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:34:09  来源:igfitidea点击:

Laravel select * where id =(select id )

laravellaravel-query-builder

提问by Ufc Champion Mohamed Abd-Elham

Using Laravel eloquent how do I make a query like this:

使用 Laravel eloquent 如何进行这样的查询:

 select * from branches where user_id =(select id from users where name ='sara' )

回答by Rwd

Assuming that you have a userrelationship in your Branchmodel you could use whereHas:

假设user您的Branch模型中有关系,您可以使用whereHas

$branches = Branch::whereHas('user', function ($query) {

    $query->where('name', 'sara');

})->get();

Hope this helps!

希望这可以帮助!

回答by MartinLeitgeb

I would split it into two queries. First getting the id, then getting the list. Expecting your models to be called "User" and "Branches"

我会把它分成两个查询。首先获取id,然后获取列表。期望您的模型被称为“用户”和“分支”

$user = User::where('name', 'sara');
$id = $user->id;
$branches = Branch::where('id', $id);

This site may help you Link

这个网站可以帮助你链接

回答by Kuldeep Mishra

 $id = Users::select('id')->where('name','sara')->first();
 $barnches = branches::where('id',$id)->get();

Here Users and branches are models , first is using for 1 row and get for many rows

这里用户和分支是模型,首先使用 1 行并获取多行

回答by Zayn Ali

Try this.

尝试这个。

$name = 'sara';

$results = BranchModel::whereIn("user_id", function ($query) use ($name) {
    $query->select("id")
        ->from((new UserModel)->getTable())
        ->where("name", $name);
})->get();