0

I am new to Laravel. Can anyone tell me how should I write this query in laravel query builder ?

SELECT users.id, customers.zip
FROM users, customers
WHERE users.id =26
AND customers.customer_id = users.user_name
1
  • I read their manual but I couldn't figure it out. :( Commented Apr 4, 2014 at 11:49

4 Answers 4

1

Simplest method is with the query builder - here's a link to a join example

As you develop your knowledge of Laravel, you'll likely start using Laravel's Eloquent ORM, in which case you'll want to read this section of the docs to learn how to define relationships between tables.

Update:

I've see your comment above above, about not being able to understand the docs. That's surprising because they're well-tested and clear in this area, but here's answer I think you're looking for:

DB::table('users')
    ->where('users.id', '=', 26)
    ->join('customers', 'customers.customer_id', '=', 'users.user_name')
    ->select('users.id', 'customers.zip');
Sign up to request clarification or add additional context in comments.

Comments

1
DB::table('users')
->join('customers','users.username', '=', 'customer.customer_id')
->select('users.id', 'customer.zip')
->where('users.id','=', '26')
->get();

this will for you.

refer this for more https://laravel.com/docs/5.2/queries

if you want to use eloquent collections refer this https://laravel.com/docs/5.2/collections#method-filter.

Comments

0

Well In your case is better to use HasOne relationship http://laravel.com/docs/eloquent#relationships You need to create Customer class

 class Customer extends Eloquent {

   //if you table is not called customers you need to add
    protected $table = 'table_name';

    }

Than in User controller

class User extends Eloquent {

        public function customers()
        {
            return $this->hasOne('Customer', 'customer_id');
        }

    }

In a nutshell laravel will find users.id(26) and join them with customer_id(26), it's easier and simpler less code in controller.

$user_id = 26; 
$user = User::find($user_id);

echo "username:".$user->user_name."user/customer zip code: ".$user->customers->zip;

This relationship is only if each user has one record in customers table(so if there will be twoo user_id 26 it will get only the first) if you want to have them more then one record for each user you need to use hasMany

Comments

0

DB::table('users as u1') ->join('customers as c1', 'c1.customer_id', '=', 'u1.user_name') ->->where('users.id', '=', 26) ->select('users.id', 'customers.zip');

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.