简体   繁体   English

在laravel中加载时,关系数组为null

[英]relationship array null when eager loading in laravel

I am having issues getting the relationship array back when eager loading in laravel 4. for example: 我在laravel 4中急切加载时遇到了关系数组的问题。例如:

controller: 控制器:

         foreach (Apps::with('extra')->get() as $app)
         {
                 print_r($app->toArray());//returns array but my relationship array at the bottom  says null
                echo $app->extra; //this will show my relationship details

        }

model: 模型:

class Apps extends Eloquent
{
    protected $connection = 'mysql_2';
    protected $table = 'apps';
    public $timestamps = false;
    protected $primaryKey = 'name';


     public function host()
     {
           return $this->belongsTo('Hosts','name');
     }

     public function extra()
     {
            $this->primaryKey='app_ip';
           return $this->hasone('Extra','ip');
     }

  //other functions below.......

}

class Extra extends Eloquent
{
    protected $connection = 'mysql_3';
    protected $table = 'extra';
    public $timestamps = false;
    protected $primaryKey = 'ip';

    public function app(){
            return $this->belongsTo('Apps', 'app_ip');
}

mysql: MySQL的:

My mysql tables were not created through laravel they were previously existent. 我的mysql表不是通过以前存在的laravel创建的。 the app_ip column in the Apps table relates to the ip column in the extra table. Apps表中的app_ip列与额外表中的ip列相关。 it is a 1 to 1 relationship and I have specified the primary key in the relationship function. 它是一对一的关系,我在关系函数中指定了主键。 I am getting relationships back so I know that it is working. 我正在恢复关系,所以我知道它正在发挥作用。

I am able to get relationship data back when I call the function directly, but it does not show the relationship data when I try and print the full array. 当我直接调用函数时,我能够获得关系数据,但是当我尝试打印完整数组时,它不会显示关系数据。 The main goal is to be able to return both the relationship columns and the app columns in one response. 主要目标是能够在一个响应中返回关系列和应用列。

You need to do this: 你需要这样做:

$apps = Apps::all();
$apps->load('extra');
foreach ($apps as $app)
{
   print_r($app->toArray()); // prints your relationship data as well
}

What you have should work and iterating through the collection or using ->load() to eager load shouldn't make a difference. 你有什么应该工作和迭代整个集合或使用 - > load()到急切负载不应该有所作为。 Are you using the visible restriction on your models? 您是否在模型上使用可见限制? If so you will need to include the relationships. 如果是这样,您将需要包含关系。

class Apps extends Eloquent {

    protected $visible = array(
        'id',
        'name',
        'created_at',
        'extra', // Make the relationship 'visible'
    );

    public function extra()
    {
        return $this->hasMany('Extra');
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM