我可以写这样的东西:
$post = Post::join(['author'])->find($postId);
$authorName = $post->author->name;
只生成一个带有内部连接的选择(没有 2 个选择)并且不使用 DB 查询生成器
SELECT
post.*,
author.*
FROM post
INNER JOIN author
ON author.id = post.author_id
WHERE post.id = ?
You can do it in Eloquent using the join
method:
$post = Post::join('author', function($join)
{
$join->on('author.id', '=', 'post.author_id');
})
->where('post.id', '=', $postId)
->select('post.*', 'author.*')
->first();
Please note that your results in $post
will be an object where their attributes will correspond to the result set, if two columns has the same name it will be merged. This happen when using:
->select('post.*', 'author.*')
To avoid this, you should create alias to those columns in the select clause as shown below:
->select('post.id AS post_id', 'author.id AS author_id')
尝试
Post::join('author',function($join){
$join->on('author.id','=','post.author_id');
})->where('post.id','=',$postId)->select('post.*','author.*');