Let's say I have a table that looks like this:
name | link
-----------
A | asdf
A | zxcv
B | qwer
B | rtyu
C | fghj
I am currently getting the results using 2 queries like the following using the $link variable:
// 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();
How can I do this in a single query?
You can use Builder::whereIn
and subqueries to achieve what you want:
Model::whereIn("name", function ($query) use ($link) {
$query->select("name")
->from((new Model)->getTable())
->where("link", $link);
})->get();
Try this
$results = Model::whereIn('name', function($query) use ($link) {
$query->from((new Model)->getTable())
->where('link', $link)
->select('name');
})->get();
OR with DB (update the table_name
with real one)
$results = DB::select(
"SELECT * FROM `table_name` WHERE `name` IN (SELECT `name` FROM `table_name` WHERE `link` = :link)",
[ "link" => $link ]
);