#PolyMorph Many To Many

6 messages · Page 1 of 1 (latest)

dull valve
#
    public function assignedUsers()
    {
        return $this->morphToMany(User::class, 'assignable', 'assignables', 'assignable_id', 'assigned_id')
            ->where('assigned_type', User::class);
    }

    public function assignedTeams()
    {
        return $this->morphToMany(Team::class, 'assignable', 'assignables', 'assignable_id', 'assigned_id')
            ->where('assigned_type', Team::class);
    }

I have to do like this to make it work.

$p->assignedUsers()->attach($u, ['assigned_type' => User::class]);

what am i doing wrong? shouldn't it know assigned_type? 😭😭
if i do without manually filling out attribute, it gives me
SQLSTATE[HY000]: General error: 1364 Field 'assigned_type' doesn't have a default value (Connection: mysql, SQL: insert into assignables (assignable_id, assignable_type, assigned_id, created_at, updated_at) values (1, App\Models\Project, 1, 2024-08-24 11:33:58, 2024-08-24 11:33:58)).

timber pulsar
#

Please share your database structure for the table

dull valve
# timber pulsar Please share your database structure for the table
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('assignables', function (Blueprint $table) {
            $table->id();
            $table->morphs('assignable');
            $table->morphs('assigned');
            $table->timestamps();

            $table->unique(
                ['assignable_id', 'assignable_type', 'assigned_id', 'assigned_type'],
                'assignables_unique'
            );
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('assignables');
    }
};
high sundial
# dull valve ```php public function assignedUsers() { return $this->morphToMa...

So your models should look like this:


class Assignable extends Model {

public function assignable(): MorphTo
{
return $this->morphTo();
}
}

Same for assigned as MorphTo

In user:

class User extends Model {

public function assigned(): MorphMany
{
  return $this->morphMany(Assignable::class, 'assigned')
}
}

same again for assignable

dull valve
#

Group is a group of tasks