Pivot tables? #337
-
What's the best way to handle pivot table data with this package? I tried looking through discussions and the documentation but I couldn't find any information on this. Would it best to create an intermediate class and model the DO after that? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
@furiouskj did you find any solution for this? |
Beta Was this translation helpful? Give feedback.
-
@kennymeyers, @moeen-basra My model class User extends Model
{
public function roles(): BelongsToMany
{
return $this->belongsToMany(Role::class)
->withPivot('field_a', 'field_b');
}
} UserData use App\Models\User;
use Spatie\LaravelData\Data;
class UserData extends Data
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly ?string $email,
#[DataCollectionOf(UserRoleData::class)]
public readonly DataCollection $roles,
){}
public static function fromModel(User $user)
{
return new self(
...$user->only([
'id',
'name',
]),
roles: UserRoleData::collection($user->roles)
);
}
} UserRoleData use App\Models\Role;
use Spatie\LaravelData\Data;
class UserRoleData extends Data
{
public function __construct(
public readonly int $id,
public readonly string $name,
public readonly string $field_a,
public readonly string $field_b,
){}
public static function fromModel(Role $role): UserRoleData
{
return new self(
$role->id,
$role->name,
$role->pivot->field_a,
$role->pivot->field_b,
);
}
} |
Beta Was this translation helpful? Give feedback.
@kennymeyers, @moeen-basra
I implemented the following solution with pivot data on a many-to-many relationship. Instead of using a DataCollection of RoleData I created a new data object called UserRoleData to make the pivot data more accessible. I then added that to my UserData object.
My model
UserData