lundi 16 juillet 2018

Laravel Many To Many Polymorphic Relation : Get child with higher priority with each record

In my Laravel 5.5 application, many to many polymorphic relation is used for pointing the relation between destinations and photos. There is a priority column in the pivot table for storing the precedence of each relation.

What I need is, access all destination records with one related photo of higher priority.

I was able to access all destination with all related photos. But when I try to narrow the selection of related item to 'one' with higher priority it doesn't work.

Migration for destinations table :

Schema::create('destinations', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 100)->unique();
    $table->string('tag_line', 200);
});

Migration for photos table :

Schema::create('photos', function (Blueprint $table) {
    $table->increments('id');
    $table->string('image_name', 100)->unique();
});

Migration for publishables table :

Schema::create('publishables', function (Blueprint $table) {
    $table->unsignedInteger('photo_id');
    // publishable_id and publishable_type
    $table->morphs('publishable');
    $table->tinyInteger('priority');
});

Destination Model :

class Destination extends Model
{
    /**
     * Get all of the images for the destination.
     */
    public function photos()
    {
        return $this->morphToMany('App\Models\Photo', 'publishable')->as('destinationPhotoDetail')->withPivot('priority');
    }
}

Photo Model :

class Photo extends Model
{
    /**
     * Get all of the destinations that are assigned this photo.
     */
    public function destinations()
    {
        return $this->morphedByMany('App\Models\Destination', 'publishable');
    }
}

Methods which I have tried :

$destinations = Destination::with(['photos']);

Output : It gives all related photos

$destinations = Destination::with(['photos' => function ($query) {
                    $query->orderBy('priority', 'desc')->first();
                }]);

Output : It gives only one photo with higher priority for only one destination.

publishables table data:

enter image description here

From this db table data,

Photo where id = 1 should be get with Destination where id = 1[only one with priority 1]

Photo where id = 2 should be get with Destination where id = 2[record with priority 2]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire