【问题标题】:One to Many Relationship in Laravel 5.5Laravel 5.5 中的一对多关系
【发布时间】:2018-08-13 12:55:18
【问题描述】:

我在 Laravel 5.5 中遇到了一对多关系的问题。

我有两张表,一张用于博客文章,一张用于作者。 posts 表有一个 author_id 列,其中填充了每篇博文的有效作者 ID。 author_id 被定义为posts表迁移中的外键。

当我加载使用查询的视图时,作者为空,因为 author_id 未包含在生成的查询中。

后模型:

public function author(): BelongsTo
{
    return $this->belongsTo(Author::class);
}

我也尝试明确列出具有相同结果的键:

return $this->belongsTo(Author::class, 'author_id', 'id');

后存储库:

public function getPostBySlug(string $slug)
{
    return $this->model
        ->select(
            'posts.title',
            'posts.contents',
            'posts.published_at'
        )
        ->with(['author:first_name,last_name,slug'])
        ->where('posts.slug', '=', $slug)
        ->whereNotNull('posts.published_at')
        ->first();
}

生成的查询:

select `first_name`, `last_name`, `slug` 
from `authors` where `authors`.`id` in ('') 
and `authors`.`deleted_at` is null

【问题讨论】:

    标签: laravel laravel-5 eloquent relationship


    【解决方案1】:

    您没有选择posts.author_id,因此如果没有author_id,则无法建立关系,例如,选择* 或排除select 语句或在您的选择语句中包含posts.author_id

    $this->model
        ->select(
            'posts.author_id',
            'posts.title',
            'posts.contents',
            'posts.published_at'
        )
        // rest of the code ...
    

    foreign key (posts.author_id) 必须可用于与authors 建立关系。

    【讨论】:

      【解决方案2】:

      试试这个

      $users = DB::table('posts')
              ->leftJoin('authors', 'authors.id', '=', 'posts.user_id')
              ->select('posts.author_id','posts.title','posts.contents','posts.published_at',
                     'authors.first_name','authors.last_name','authors.slug')
              ->where('posts.slug', '=', $slug)
              ->whereNotNull('posts.published_at')
              ->first();
      

      【讨论】:

        【解决方案3】:

        按以下方式整理关系 :

        return $this->belongsTo('namespace\author');
        

        或相反的方式

        return $this->hasMany('namespace\author');
        

        【讨论】:

          猜你喜欢
          • 2018-03-16
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-02-02
          • 2018-05-22
          • 1970-01-01
          • 2019-01-30
          • 1970-01-01
          相关资源
          最近更新 更多