TheCodingKid
TheCodingKid

Reputation: 115

Laravel One to Many relationship for system

I want to output all the reviews based on one hotel of my system. Currently, I have a system which displays ALL reviews on each hotels. I have the following code:

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

I want to return matching reviews for the right hotel. I want to return posts_title (main column in posts table) and return the title (column in the reviews table).

Upvotes: 0

Views: 81

Answers (2)

TsaiKoga
TsaiKoga

Reputation: 13394

You have an error with your relationship, check the one-to-many reference In your Post Model:

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

In your Review Model:

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

And you can use eager-loading:

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

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

Upvotes: 0

aibarra
aibarra

Reputation: 419

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

Upvotes: 1

Related Questions