I have two tables at db, one of them is named users
which simply contains user information of website and the other one is tags
which contains some hashtags that users can choose from them.
I also created a table named tag_user
that can store the tag_id
and user_id
like this image:
(just like Stackoverflow that a user can select multiple tags such as php, javascript & etc)
So in order to make this relationship between these two, I added this to User
model:
public function tags() { return $this->belongsToMany(User::class); }
And also this one to Tag
model:
public function users() { return $this->belongsToMany(Tag::class); }
And here is the select option on blade, and users can select multiple tags from db:
<select class="form-control BSinaBold" name="skills[]" id="skills" multiple> @foreach(AppModelsTag::all() as $tag) <option value="{{ $tag->id }}" {{ in_array($tag->id , Auth::user()->tags->pluck('id')->toArray()) ? 'selected' : '' }}>{{ $tag->name }}</option> @endforeach </select>
Now as soon as I load the blade, I got this as error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table ‘dbname.user_user’ doesn’t exist (SQL: select users
.*, user_user
.user_id
as pivot_user_id
from users
inner join user_user
on users
.id
= user_user
.user_id
where user_user
.user_id
= 4)
So what’s going wrong here? How can I fix this issue?
I would really appreciate any idea or suggestion from you guys…
And here is also the migration of tags
& tag_user
table:
public function up() { Schema::create('tags', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('label'); $table->timestamps(); }); Schema::create('tag_user', function (Blueprint $table) { $table->unsignedBigInteger('tag_id'); $table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade'); $table->unsignedBigInteger('user_id'); $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade'); $table->primary(['tag_id','user_id']); }); }
Thanks in advance.
Advertisement
Answer
As @aynber described in the comments:
In User
model
public function tags() { return $this->belongsToMany(Tag::class); }
And in Tag
model
public function users() { return $this->belongsToMany(User::class); }