lundi 5 mars 2018

One to Many Relationship in Laravel 5.5

I'm having trouble with a one-to-many relationship in Laravel 5.5.

I have two tables, one for blog posts and one for authors. The posts table has an author_id column and it's populated with valid author IDs for each blog post. author_id is defined as a foreign key in the posts table migration.

When I load a view that uses the query the author is null because the author_id isn't being included in the generated query.

Post model:

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

I also tried explicitly listing the keys with the same result:

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

Post repository:

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

Generated query:

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



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2I1luYF
via IFTTT

Aucun commentaire:

Enregistrer un commentaire