-1

I want to get all unique combinations of color_code.code and manufacturer_bundle.name that exist. They are connected via a table manufacturer

this is my current code.

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

The problem with it, is, that the select returns only those fields, and not actually the models. So I want to be able to do this:

$color_code->manufacturer->name

which gives me

Trying to get property of non-object

for completeness:

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();
    });

Manufacturer

 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();
    });
Toskan
  • 13,911
  • 14
  • 95
  • 185
  • see here http://stackoverflow.com/questions/11277251/selecting-distinct-2-columns-combination-in-mysql – Toskan Sep 23 '16 at 21:37

2 Answers2

0

Only eloquent objects can have relationships, not collections.

The results of your query are collections, not Eloquent objects, because you are combining two tables. So of course you cannot "inherit" model relationships for combinations of data. You would have to create a new model for linking color codes with manufacturers for that to work, or find ColorCode from the specified dataset by hand:

$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;
}
Tadas Paplauskas
  • 1,863
  • 11
  • 15
  • apart from this being ineffective, it wouldn't work. Because the unique combination constraint is not fullfilled – Toskan Sep 23 '16 at 19:40
0

I think you can use hasManyThrough relationship. Laravel Has Many Through

In your ColorCode model add the following method to define hasManyThrough relationship. Note: Assuming you have ManufacturerBundle model for table manufacturer_bundle and Manufacturer for manufacturer table.

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

Now, in your controller you can use following method to retrieve the manufacturer_bundle.

$color_codes = ColorCode::with('manufacturer_bundle')->get();
jaysingkar
  • 4,315
  • 1
  • 18
  • 26