【发布时间】: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