Laravel Eloquents关系查询获取所有字段数据

时间:2014-09-19 08:26:32

标签: mysql laravel-4 foreign-keys eloquent

还在尝试使用Eloquents关系查询,我想知道如果结构如下,我在查询结果中如何得到过渡表中的setup字段

拥有广告系列campaign_networks_relationhsips

+----------------------------------------------------------------------------------+
 ID | networks_id | campaigns_id | setup                                         
+----------------------------------------------------------------------------------+
 1  | 1           | 1            | {"username":"username","password":"password"} 
+----------------------------------------------------------------------------------+
 2  | 1           | 2            | {"username":"username","password":"password"} 
+----------------------------------------------------------------------------------+

广告活动

+-------------------+
 ID | campaign_name                                          
+-------------------+
 1  | some name 
+-------------------+
 2  | test 
+-------------------+

网络

+-------------------+
 ID | network_name                                          
+-------------------+
 1  | network1 
+-------------------+
 2  | network2 
+-------------------+

比我的Camnpaigns模型

public function networks() {
    return $this->belongsToMany('Td\Reports\Networks\Networks',  'campaign_networks_relationhsips');
}

从控制器调用

   public function getNetworks($id = null) {
        $campaign = \Td\Reports\Campaigns\Campaigns::with('networks')->where('id', $id)->first();
        foreach ($campaign->networks as $network) {
             var_dump($network->network); //I have this Field
             var_dump($network->setup); // I do not habe this Field !!!!
        }

    }

1 个答案:

答案 0 :(得分:0)

public function networks() {
    return $this->belongsToMany('Td\Reports\Networks\Networks',  'campaign_networks_relationhsips')
       ->withPivot(['setup', .. any other field you might want .. ]);
}

// then in the foreach loop you have:
...
   $network->pivot->setup;