Ad
Laravel 6.9 BelongsToMany Relationships Return One Collection
I have Many To Many Relationships. I have three tables:
posts
posts_tag
tags
Table "posts" have standart fields.
The structure of the table "posts_tag":
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('post_id')->unsigned();
$table->foreign('post_id')->references('id')->on('posts');
$table->bigInteger('tag_id')->unsigned();
$table->foreign('tag_id')->references('id')->on('tags');
});
The structure of the table "tags":
Schema::create('tags', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
The relationship is defined in the model:
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
}
}
I call the method $tag->posts
:
public function getPostsByTag($id)
{
$tag = Tag::find($id);
dd($tag->posts);
}
I get only one array:
Illuminate\Database\Eloquent\Collection {#571 ▼
#items: array:1 [▶]
}
I will be grateful for any help friends! If you're sorry for my English, I'm in the process of learning!
Ad
Answer
In your Tag modal
class Tag extends Model
{
public function posts()
{
return $this->belongsToMany(Post::class,'post_tag', 'post_id', 'tag_id');
}
}
In your Post modal
class Post extends Model
{
public function tags()
{
return $this->belongsToMany(Tag::class,'post_tag', 'tag_id', 'post_id');
}
}
In your controller
public function getPostsByTag($id)
{
$tag = Post::with('tags')->find($id);
dd($tag);
}
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad