0

我有 3 个表:用户、项目、项目和朋友。我想获取一个项目的所有项目并将每个项目与相关朋友列出。我的模型中是否缺少某些内容?最终我想得到所有与项目相关的朋友。

// 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();
4

2 回答 2

0

乍一看,您的模型似乎还可以。我想既然你在拉关系item.friend,这条线

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

应该,

@foreach ($project->item->friend as $friend)
于 2013-11-10T16:24:46.010 回答
0

你错过了一个循环。我建议在建立多对多关系时,确保你的方法是复数的。尝试阅读代码时更有意义。然后你会用@foreach $project->items as $itemor发送$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
于 2013-11-11T16:07:22.347 回答