简体   繁体   English

查询生成器加入并获取指定的记录laravel

[英]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: 要使用Eloquent实现此目的,请执行以下操作:

I'm assuming you're using the latest Laravel version (5.1) 我假设您使用的是最新的Laravel版本(5.1)

1. You need a Model for the User and the UserDetails: 1.您需要一个用于用户和UserDetails的模型:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model {}

2. Set up the relationship between them 2.建立它们之间的关系

User.php user.php的

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

UserDetail.php UserDetail.php

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

3. Query the relationship: 3.查询关系:

eg UserController.php 例如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. 或者,您可以使用where指定where子句。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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