Laravel:使用eloquent从多个相关表中返回结果

时间:2013-07-31 07:57:10

标签: php laravel laravel-4 eloquent

我正在使用Laravel 4,特别是我正在寻找一个使用雄辩的ORM的答案。

我有一个表格“任务”,其中包含分配给每一行的 client_id user_id

client_id 是指“客户”表中的客户, user_id 是指“用户上的用户“表。

我想做什么:显示所有任务并显示“客户名称和“用户 first_name

所以结果在我的(刀片)视图中看起来像这样:

@foreach($tasks as $task)
    <tr>
        <td>{{ $task->user->first_name }}</td>
        <td>{{ $task->client->name }}</td>
        <td>{{ $task->description }}</td>
    </tr>
@endforeach

上面的视图完全排除$ task-&gt; client-&gt;名称,但不幸的是,当我添加行$ task-&gt; user-&gt; first_name时,显示“试图获取非对象的属性”

我的控制器看起来像这样:

$tasks = Task::with(array('user', 'client'))->get();
return View::make('index', compact('tasks'));

据我了解,我的模型也有所不同,所以我的模型看起来像这样:

class Task extends Eloquent {
    protected $guarded = array();
    public static $rules = array();

    public function client() {
        return $this->belongsTo('Client');
    }

    public function user() {
        return $this->belongsTo('User');
    }
}

class User extends Eloquent implements UserInterface, RemindableInterface {
    public function task()
    {
        return $this->hasMany('Task');
    }
}

class Client extends Eloquent {
    public function projects(){
        return $this->hasMany('Project', 'client_id');
    }
}

关于如何使这项工作的任何想法?我一直在摸不着头脑 - 还注意我不是数据库关系亲,所以解释越简单越好:)< / p>

2 个答案:

答案 0 :(得分:2)

我刚刚完成了这项工作并且自己学到了很多东西。我所做的是设置usersclients之间的多对多关系,并创建了一个数据透视表来处理名为tasks的关系,该关系也存储了每个任务的描述。

在此输入太多了,但您可以在http://paste.laravel.com/Fpv

查看我的代码

答案 1 :(得分:0)

使用Eloquent可以像这样做多对多的关系:

class User extends Eloquent implements UserInterface, RemindableInterface {
    public function client()
    {
        return $this->belongsToMany('Client', 'tasks', 'client_id')->withPivot('description');
    }
}

和反向关系...

class Client extends Eloquent {
    public function users()
    {
        return $this->belongsToMany('User', 'tasks', 'user_id');
    }
}

没有测试过,但它应该是正确的。