0

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?

2
  • what's the use case you have? Is the $link submitted from a form or something? Commented Aug 1, 2017 at 17:59
  • $link is a partial url Commented Aug 1, 2017 at 18:01

2 Answers 2

3

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();
Sign up to request clarification or add additional context in comments.

1 Comment

If I wanted to do a "leftJoin" on the "with(new Model)" part, how would I go about doing this?
1

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 ]
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.