2017-03-01 79 views
0

我正在使用Laravel 5.3並嘗試使用連接從多個表中返回數據。在Laravel中返回深嵌套關係中的選定列

我使用3種型號/桌,客戶,業務和相關的網站如下:

在Customer.php:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Customer extends Model 
{ 
    public function businesses() 
    { 
    return $this->hasMany('App\Business'); 
    } 
} 

在Business.php:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Business extends Model 
{ 
    public function customer() 
    { 
    return $this->belongsTo('App\Customer'); 
    } 

    public function websites() 
    { 
    return $this->hasMany('App\Website'); 
    } 
} 

而在Website.php中:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Website extends Model 
{ 
    public function business() { 
    return $this->belongsTo('App\Business'); 
    } 
} 

所以一個Customer可以有很多Businesses,它可以有很多Websites

現在我試圖返回Customer,BusinessWebsite(理想情況下)一個Eloquent請求中的某些列。我知道我可以使用所有表中返回所有列一個簡單的貪婪加載像這樣:

Customer::with('businesses.websites'); 

但我只想要回某些列,並返回一個數組的數組,像這樣:

[ 
    0 => { 
    'first_name' => 'John', 
    'last_name' => 'Smith, 
    'email' => '[email protected]', 
    'businesses' => [ 
     0 => { 
     'name' => 'Smith Ltd' 
     'websites' => [ 
      0 => { 
      'domain' => 'smithltd', 
      'tld' => '.co.uk' 
      } 
     ] 
     } 
    ] 
    } ... 
] 

即忽略IDS,外鍵,created_at時間戳等等等等

我一直想這個使用下面的代碼(及其變型)來實現:

Customer::with([ 
    'businesses' => function ($q) { 
     $q->select('id', 'customer_id')->pluck('name'); 
    }, 
    'businesses.websites' => function ($q) { 
     $q->select('id', 'business_id')->pluck('domain', 'tld'); 
    } 
    ])->get(); 

但是,這也是我不想要的idcustomer_idbusiness_id。據我所知,我需要在select查詢中添加foreign_keyprimary_key以使查詢正常工作,但是有沒有辦法將它從最終返回的集合中刪除?或者有更好的方法來解決這個問題嗎?任何幫助將不勝感激,非常感謝。

+0

檢查:http://stackoverflow.com/questions/30216763/laravel-many-to-many-unexpected-result-set-on-select/30218621#30218621 – Troyer

+0

這不是PHP的答案,但有你考慮爲這些信息製作一個數據庫視圖,以及爲特定用例引用視圖的模型? –

+0

另外,如果你的用例只是通過API返回,那麼你可能會考慮分形 –

回答

0

你可以做一個rray_merge與你的商業模式

創建新的函數

public function getArrayWithCustomerAndWebsites() 
    { 
    return array_merge("customer" => $this->customer(), etc.....); 
    } 

希望它可以幫助你!