Laravel 5.5中的一对多关系

时间:2018-03-05 19:08:07

标签: laravel laravel-5 eloquent relationship

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

我有两个表,一个用于博客帖子,另一个用于作者。 posts表有一个author_id列,并且每个博客帖子都填充了有效的作者ID。 author_id被定义为posts表迁移中的外键。

当我加载使用查询的视图时,作者为null,因为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

3 个答案:

答案 0 :(得分:2)

您未选择posts.author_id,因此如果无法author_id无法建立关系,请选择*或排除select语句或包含{{在您的select语句中输入1}},例如:

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)建立关系。

答案 1 :(得分:0)

试试这个

$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();

答案 2 :(得分:0)

以下列方式托盘 :

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

或反向

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