Skip to content

Instantly share code, notes, and snippets.

@atayahmet
Last active July 30, 2016 13:19
Show Gist options
  • Save atayahmet/1eb8c85840f7a6a4065fad31280b2162 to your computer and use it in GitHub Desktop.
Save atayahmet/1eb8c85840f7a6a4065fad31280b2162 to your computer and use it in GitHub Desktop.

Tags Relation

## Get the product tags

Tag relation in product model:

<?php

public function tags()
{
    return $this->morphToMany(Tag::class, 'taggable', 'tag_relation', 'relationid', 'tag_id')
        ->withTimestamps()
        ->where('relation_type', 'product')
        ->where('gender_type', 2); // bayan 
}
<?php

$product = App\Models\Product::with('tags')->find(1);

Get products by tags

Products relation in tag model:

<?php

public function products()
{
    return $this->morphedByMany(Product::class, 'taggable', 'tag_relation', 'tag_id', 'relationid')
        ->withTimestamps()
        ->where('relation_type', 'product');
}
<?php

App\Models\Tag::with('products')->where('name', 'kırmızı')->get()

Save into pivot table

<?php

$product = App\Models\Product::find(1);
$tag = new App\Models\Tag(['name' => 'Kırmızı']);

$product->tags()->save($tag, ['gender_type' => 1, 'relation_type' => 'product'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment