返回相关领域[Laravel 4]

时间:2014-09-10 00:24:36

标签: php laravel-4 relationship blade belongs-to

我有两个这样的模型:

class Task extends Eloquent {

    protected $guarded = ['id'];

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

class User extends Eloquent {

    protected $guarded = ['id'];

    public function task() {
        return $this->hasMany('Task');
    }
}

..和一个看起来像这样的刀片索引部分:

@foreach ($tasks as $task)

    {{ "<tr><td>$task->user->fullname</td></tr>" }}

@endforeach

...但是它不是返回全名,而是返回整个JSON对象,如...

{"id":9,"email":"FunkB@example.com","fullname":"Brycen Funk","created_at":"2014-09-09 16:40:31","updated_at":"2014-09-09 16:40:31"}->fullname

对我做错了什么的想法?我提前道歉,因为我确信答案是显而易见的,就在我眼前。

感谢。

1 个答案:

答案 0 :(得分:0)

当您使用Eloquent从数据库中获取任务时,您是否急于加载用户?如果没有,要做到这一点,你只需要做这些事情:

$tasks = Task::with(['user'])->get();

或者您可以在foreach循环中执行此操作:

@foreach ($tasks as $task)
<tr>
    <td>{{ $task->user()->fullname }}</td>
</tr>
@endforeach