Laravel系统一对多关系

时间:2020-02-01 14:01:55

标签: laravel

我想基于系统中的一家酒店输出所有评论。目前,我有一个显示所有酒店评论的系统。我有以下代码:

PostsController:

public function show($id)
{
    $post = Post::find($id);
    $review = Review::all();

    return view('posts.show', compact('post', 'review'));      
    /** return view('posts.show')->with('post', $post); */
}

Posts.php:

protected $tables='posts';
function review()
{
    return $this->hasMany('App\Review');
}

Review.php:

protected $tables='reviews';
function post()
{
    return $this->hasMany('App\Post', 'posts_title', 'title');
}

我想为合适的酒店返回匹配的评论。我想返回posts_title(在posts表中的主列)并返回title(在reviews表中的列)。

2 个答案:

答案 0 :(得分:1)

Reviews.php

protected $tables ="posts";
public function reviews()
{
    return $this->hasMany('App\Reviews', 'foreign_id', 'id_here');
}

PostsController

public function show($title)
{
    $post = Posts::where('title', '=', $title)->with('reviews')->first();
    return view('show.blade', compact('post'));
}

答案 1 :(得分:0)

您的恋爱关系有误,请检查one-to-many reference 在您的帖子模型中:

function reviews()
{
    return $this->hasMany('App\Review');
}

在您的评论模型中:

protected $tables='reviews';
function post()
{
    return $this->belongsTo('App\Post', 'post_id', 'id');
}

您可以使用eager-loading:

public function show($id)
{
    $post = Post::with('reviews')->find($id);

    return view('posts.show', compact('post'));
}