【问题标题】:Laravel 4.2 oneToMany relationship issueLaravel 4.2 oneToMany 关系问题
【发布时间】:2015-06-18 13:40:32
【问题描述】:

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

关系是一个任务有一个主题,主题有很多任务。

任务模型

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) { } [“连接”:受保护]=> NULL [“表”:受保护]=> NULL ["primaryKey":protected]=> 字符串(2) "id" ["perPage":protected]=> int(15) ["递增"]=> 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) "你想让我们收集 Moss?" ["objective"]=> string(36) "收集信息包括 Q&A" ["method"]=> string(29) "支持的历史研究" ["context"]=> string(0) "" ["level"]=> string(0) "" ["created_at"]=> 字符串(19)“0000-00-00 00:00:00”[“updated_at”]=>字符串(19) “0000-00-00 00:00:00”} [“原始”:受保护]=> 数组(11){ [“id”]=> 字符串(1)“9”[“数字”]=>字符串(1)“6”[“主题”]=>字符串(1)“2” ["topic_old"]=> string(10) "战争努力" ["task"]=> string(28) "你 要我们收集苔藓吗?" ["objective"]=> string(36) "收集 包括问答在内的信息" ["method"]=> string(29) "支持 历史研究" ["context"]=> string(0) "" ["level"]=> string(0) "" ["created_at"]=> 字符串(19) "0000-00-00 00:00:00" ["updated_at"]=> 字符串(19)“0000-00-00 00:00:00”}[“关系”:受保护]=>数组(0) { } [“隐藏”:受保护]=> 数组(0){ } [“可见”:受保护]=> 数组(0){}[“附加”:受保护]=>数组(0){} ["fillable":protected]=> array(0) { } ["dates":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> 数组(0) { } ["with":protected]=> 数组(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) ["softDelete":protected]=> bool(false) }

【问题讨论】:

  • 数据库任务表有topic_id

标签: laravel laravel-4 eloquent


【解决方案1】:

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

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

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

我想将变量更改为$tasks,因为使用 where(),您将立即获得 Illuminate\Database\Eloquent\Collection(很多结果)

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

dd($tasks->get());

【讨论】:

    猜你喜欢
    • 2016-09-20
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2013-04-03
    • 2016-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    相关资源
    最近更新 更多