简体   繁体   English

使用Laravel 4检索相关模型

[英]Retrieve Related Models using Laravel 4

I have 3 tables: Users, Projects, Items and Friends. 我有3个表格:Users,Projects,Items和Friends。 I want to get all the items for a project and list each item with related friends. 我想获取一个项目的所有项目,并与相关的朋友列出每个项目。 Am I missing something in my model? 我的模型中缺少什么吗? Ultimately I want to get all the friends which are related to the items. 最终,我希望得到与这些物品相关的所有朋友。

// CONTROLLER

public function show($id)
{
    $uid = Auth::user()->id;

    $projects = Project::find($id)->with('item.friend')->get();

    return View::make('projects.show', compact('projects'));
}

//VIEW

@foreach ($projects as $project)
    @foreach ($project->friend as $friend)

        <li>

            <a href="#" class='itemLink' >{{$friend->email}}</a>

            <a href="#" class='itemLink' >{{$projects->item->name}}</a>

        </li>
    @endforeach
@endforeach

// MODELS

class User extends Eloquent {

    public function project()
    {
        return $this->hasMany('Project');
    }

    public function item()
    {
        return $this->hasMany('Item');
    }

        public function friend()
    {
        return $this->hasMany('Friend');
    }



class Project extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

    public function item()
    {
        return $this->hasMany('Item');
    }

        public function friend()
    {
        return $this->hasMany('Friend');
    }

class Item extends Eloquent {

    protected $guarded = array();

    public static $rules = array();


    public function friend()
    {
        return $this->hasMany('Friend');
    }

class Friend extends Eloquent {
    protected $guarded = array();

    public static $rules = array();

Your models seems OK at first look. 乍一看,您的模型似乎还可以。 I think since you are pulling item.friend relationship, this line 我认为既然您正在建立item.friend关系,这条线

@foreach ($project->friend as $friend)

should be, 应该,

@foreach ($project->item->friend as $friend)

You are missing a loop. 您错过了一个循环。 I recommend that when setting up a many to many relationship, make sure your method is plural. 我建议在建立多对多关系时,请确保您的方法是复数形式。 It makes a lot more sense when trying to read the code. 尝试阅读代码时,这更有意义。 You'd then send up with @foreach $project->items as $item or $item->friends as $friend . 然后,您可以将@foreach $project->items as $item或者将$item->friends as $friend

@foreach ($projects as $project)
    @foreach ($project->item as $item)
        @foreach($item->friend as $friend)

        <li>

            <a href="#" class='itemLink' >{{$friend->email}}</a>

            <a href="#" class='itemLink' >{{$item->name}}</a>

        </li>
        @endforeach
    @endforeach
@endforeach

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM