2016-09-23 62 views
-1

我想獲得存在的所有color_code.code和manufacturer_bundle.name的唯一組合。他們通過一個表製造商連接篩選2列以獲得獨特組合的方法!與laravel /雄辯

這是我目前的代碼。

$color_codes = ColorCode::select(['color_code.code', 'manufacturer_bundle.name'])->distinct() 
    ->leftJoin('manufacturer_bundle', 'color_code.manufacturer_id' , '=' , 'manufacturer_bundle.id') 
->get(); 

問題它,是,只有選擇那些收益領域,而不是實際的模型。所以,我希望能夠做到這一點:

$color_code->manufacturer->name 

這給了我

試圖讓非對象

財產的完整性:

的ColorCode:

Schema::create('color_code', function (Blueprint $table) { 
     $table->increments('id'); 
     $table->string('code'); 
     $table->index('code'); 
     $table->integer('manufacturer_id'); 
     $table->index('manufacturer_id'); 
     $table->timestamps(); 
    }); 

製造商

Schema::create('manufacturer', function (Blueprint $table) { 
     $table->bigIncrements('id'); 
     $table->string('name'); 
     $table->index('name'); 
     $table->integer('manufacturer_bundle_id')->nullable(); 
     $table->index( 'manufacturer_bundle_id'); 
     $table->timestamps(); 
    }); 
+0

看到這裏http://stackoverflow.com/questions/11277251/selecting-distinct-2-columns-combination-in-mysql從 – Toskan

回答

0

只有雄辯的對象可以有關係,而不是集合。

查詢的結果是集合,而不是Eloquent對象,因爲您要合併兩個表。所以當然你不能「繼承」數據組合的模型關係。你將不得不手動創建一個新的模型與製造商鏈接顏色代碼爲工作,或找到指定的數據集的ColorCode:

$color_codes = ColorCode::select(['color_code.code', 'manufacturer_bundle.name'])->distinct() 
    ->leftJoin('manufacturer_bundle', 'color_code.manufacturer_id' , '=' , 'manufacturer_bundle.id') 
->get(); 

foreach ($color_codes as $color_data) { 
    $color_code = ColorCode::where('code', color_data->code)->first(); 
    echo $color_code->manufacturer->name; 
} 
+0

除了這是無效的,這是行不通的。由於獨特的組合約束不滿足 – Toskan

0

我認爲你可以使用hasManyThrough關係。 Laravel Has Many Through

在您的ColorCode模型中添加以下方法來定義hasManyThrough關係。 注意:假設您有和ManufacturermanufacturerManufacturerBundle模型。現在

public function manufacturer_bundle(){ 
    return $this->hasManyThrough(ManufacturerBundle::class,Manufacturer::class); 
} 

,在你的控制器,你可以用下面的方法來檢索manufacturer_bundle

$color_codes = ColorCode::with('manufacturer_bundle')->get(); 
+0

需要區分的結果如何?那需要是唯一的組合 – Toskan

+0

@Toskan jsu添加'distinct()'方法 – jaysingkar