我们假设我有一张如下表:
name | link
-----------
A | asdf
A | zxcv
B | qwer
B | rtyu
C | fghj
我目前使用$ link变量使用以下2个查询获取结果:
// first query to get the row so I have the name
$m = Model::where('link', '=', $link)->get();
// using the name, I get the rows I need
$results = Model::where('name', '=', $m->name)->get();
如何在单个查询中执行此操作?
答案 0 :(得分:3)
您可以使用Builder::whereIn
和子查询来实现您的目标:
Model::whereIn("name", function ($query) use ($link) {
$query->select("name")
->from((new Model)->getTable())
->where("link", $link);
})->get();
答案 1 :(得分:1)
试试这个
$results = Model::whereIn('name', function($query) use ($link) {
$query->from((new Model)->getTable())
->where('link', $link)
->select('name');
})->get();
或与DB (用真实的table_name
更新
$results = DB::select(
"SELECT * FROM `table_name` WHERE `name` IN (SELECT `name` FROM `table_name` WHERE `link` = :link)",
[ "link" => $link ]
);