简体   繁体   中英

Laravel Join tables using Where

I would like to make a join like this. where do i go wrong ?

<?php
    for($i=1; $i<=$someValue; $i++){
              $allProjectsList = DB::table('user')
                         ->join('firstTable', 'user.id', '=','firstTable.id')
                         ->join('secondTable', 'user.pidm', '=','secondTable.id') 
                         //->where('id', '=', '$anotherValue')
                         ->first();
                         $anotherValue++;
    }
?>

---Update---

This one works nicely but,

<?php
        for($i=1; $i<=$someValue; $i++){
                  $allProjectsList = DB::table('user')
                             ->join('firstTable', 'user.id', '=','firstTable.id')
                             ->join('secondTable', 'user.pidm', '=','secondTable.id') 
                             ->where('user.id', '=', '123456')
                             ->first();
        }
?>

I would like to use a variable like $x instead of '123456', but it doesn't work. Any suggestions ?

Using a where statement with first does work actually. But it will only return a single user model where as a get will return an array of collection objects. This array can hold zero, one, or many user models.

I think one of the main issue you have is that you have your query (which returns one model) in a loop. Queries in loops should always be avoided and I honestly can't even tell why you have it in a loop, as the $i isn't even used and then you overwrite the $allProducts value every iteration through the loop.

Without more information and context I can't really help you further (other than what you seem to have figured for yourself), but I thought it'd important to have an answer with correct information about first and where's for others who come to this question for help.

Another note is that you seem to be using a user model as something other than a user model. And I would encourage you to look into relationships because you really shouldn't be returning multiple user modals with the one user id. http://laravel.com/docs/4.2/eloquent

Using where statement with ->first() does not work. Gotta use where statement with ->get()
This one solved my problem :

<?php
   $allProjectsList = DB::table('user')
                             ->join('firstTable', 'user.id', '=','firstTable.id')
                             ->join('secondTable', 'user.pidm', '=','secondTable.id') 
                             ->where('user.id', '=', $aVariable)
                             ->get();

  foreach($allProjectsList as $rowValues){
     echo('$rowValue->someJoinedFieldValue');
  }
?>


Thank you for sharing your ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM