[英]query builder join and get the specified record laravel
我正在连接两个表,然后找到指定的记录,但不幸的是它不起作用。
$users = DB::table('users')
->join('user_details', 'users.id', '=', 'user_details.id')
//->select('users.*', 'contacts.phone', 'orders.price')
->get()->find(1);
有什么建议吗?
要使用Eloquent实现此目的,请执行以下操作:
我假设您使用的是最新的Laravel版本(5.1)
1.您需要一个用于用户和UserDetails的模型:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model {}
2.建立它们之间的关系
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.查询关系:
例如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');
}
}
我认为,正确的查询将如下所示:
$users = DB::table('users')
->find(1)
->join('user_details', 'users.id', '=', 'user_details.id')
->get();
或者,您可以使用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.