【问题标题】:Can I query relations using an INNER JOIN instead of two queries in Eloquent?我可以在 Eloquent 中使用 INNER JOIN 而不是两个查询来查询关系吗?
【发布时间】:2013-08-15 06:00:09
【问题描述】:

我可以这样写吗:

$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 = ?

【问题讨论】:

  • 所以关系 $this->belongsTo('Author') 将产生 2 个 Select 查询。我想在与 post 相同的 sql-query 中获取作者信息。

标签: php orm laravel laravel-4 eloquent


【解决方案1】:

你可以在 Eloquent 中使用 join 方法来实现:

$post = Post::join('author', function($join)
    {
        $join->on('author.id', '=', 'post.author_id');
    })
    ->where('post.id', '=', $postId)
    ->select('post.*', 'author.*')
    ->first();

请注意,$post 中的结果将是一个对象,其属性将对应于结果集,如果两列具有相同的名称,它将被合并。使用时会发生这种情况:

->select('post.*', 'author.*')

为避免这种情况,您应该在 select 子句中为这些列创建别名,如下所示:

->select('post.id AS post_id', 'author.id AS author_id')

【讨论】:

    【解决方案2】:

    试试

    Post::join('author',function($join){
      $join->on('author.id','=','post.author_id');
    })->where('post.id','=',$postId)->select('post.*','author.*');
    

    【讨论】:

    • 只是为了通知如果两列共享相同的名称,它将被合并。为避免这种情况,select 子句应包含这些列的别名。
    猜你喜欢
    • 2015-10-29
    • 2017-05-03
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 1970-01-01
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多