2016-09-23 20 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