Laravel 4.2 oneToMany 关系问题

Laravel 4.2 oneToMany relationship issue

尽管已经实施了许多 L4 关系并且它们大部分时间都在工作。我正在挣扎,出于某种原因看不出我哪里出了问题。这几乎可以肯定是显而易见的。

关系是一个task有一个topic,topic有很多task。

任务模型

class Task extends Eloquent {


    protected $guarded = array();

    public static $rules = array(

    );

    public function resources()
    {
        return $this->belongsToMany('Resource');
    }


    public function topic()
    {
        return $this->belongsTo('Topic', 'topic_id');
    }

    }

主题模型

class Topic extends Eloquent {

    protected $guarded = array();

    public static $rules = array();


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

}

任务控制器

 public function show($id)
    {
        $task = $this->task->where('number', $id);

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

当我 dd ($task) 时,关系数组为空。

object(Task)#688 (21) { ["guarded":protected]=> array(0) { } ["connection":protected]=> NULL ["table":protected]=> NULL ["primaryKey":protected]=> string(2) "id" ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(11) { ["id"]=> string(1) "9" ["number"]=> string(1) "6" ["topic"]=> string(1) "2" ["topic_old"]=> string(10) "War Effort" ["task"]=> string(28) "You want us to collect Moss?" ["objective"]=> string(36) "Collecting Information including Q&A" ["method"]=> string(29) "Supported historical research" ["context"]=> string(0) "" ["level"]=> string(0) "" ["created_at"]=> string(19) "0000-00-00 00:00:00" ["updated_at"]=> string(19) "0000-00-00 00:00:00" } ["original":protected]=> array(11) { ["id"]=> string(1) "9" ["number"]=> string(1) "6" ["topic"]=> string(1) "2" ["topic_old"]=> string(10) "War Effort" ["task"]=> string(28) "You want us to collect Moss?" ["objective"]=> string(36) "Collecting Information including Q&A" ["method"]=> string(29) "Supported historical research" ["context"]=> string(0) "" ["level"]=> string(0) "" ["created_at"]=> string(19) "0000-00-00 00:00:00" ["updated_at"]=> string(19) "0000-00-00 00:00:00" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["softDelete":protected]=> bool(false) }

您需要调用之前在模型中声明的关系。在这种情况下,我将使用 Eager Loadingwith() 函数。

$tasks = $this->task->where('number', $id)->with('topic');

来源:http://laravel.com/docs/4.2/eloquent#eager-loading

I would like to change the variable to $tasks because using where(), you will get instant of Illuminate\Database\Eloquent\Collection (many results)

您可以通过以下方式查看结果。

dd($tasks->get());