简体   繁体   中英

query builder join and get the specified record laravel

I'm joing two table and then find the specified record but unfortunately it doesnt work.

$users = DB::table('users')
        ->join('user_details', 'users.id', '=', 'user_details.id')
        //->select('users.*', 'contacts.phone', 'orders.price')
        ->get()->find(1);

any ideas help?

To achieve this using Eloquent, do the following:

I'm assuming you're using the latest Laravel version (5.1)

1. You need a Model for the User and the UserDetails:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model {}

2. Set up the relationship between them

User.php

function details()
{
    // for this to work, the user_details table needs a column user_id
    return $this->hasMany('App\UserDetail');
}

UserDetail.php

function user()
{
    return $this->belongsTo('App\User');
}

3. Query the relationship:

eg UserController.php

<?php

namespace App\Http\Controllers;

use App\User;

class UserController {
    public function index()
    {
        $user = User::find(1);
        $user_details = $user->details;

        // or

        $user = User::find(1)->with('details');

    }
}

I think, the correct query will be like below:

$users = DB::table('users')
    ->find(1)
    ->join('user_details', 'users.id', '=', 'user_details.id')
    ->get();

Or you can use where to specify where clauses.

$users = DB::table('users')
    ->where('user.gender', '=', 1) // Example.
    ->join('user_details', 'users.id', '=', 'user_details.id')
    ->get();

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