Laravel

Laravel 模型关系:远程一对多

配套视频地址:https://www.bilibili.com/video/av73028135?p=5


简单的说:Thread 模型可以通过 Author 模型访问多个的 Book 模型

threads: id, title
authors: id, name, thread_id
books: id, name, author_id

模型

# App\Thread
public function authorBook()
{
    return $this->hasManyThrough('App\Book', 'App\Author');
}
# App\Thread
public function authorBooks()
{
    return $this->hasOneThrough(
        'App\Book',
        'App\Author',
        'thread_id', // 作者表外键
        'author_id', // 书表外键
        'id',        // 帖子本地键
        'id',        // 作者本地键
    );
}

使用

$books = \App\Thread::find(2)->authorBooks;
$threadsWithBooks = \App\Thread::with('authorBooks')->get();

发表评论