Laravel系统一对多关系 [英] Laravel One to Many relationship for system

查看:91
本文介绍了Laravel系统一对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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).

推荐答案

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

这篇关于Laravel系统一对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆