booni3's avatar

Attaching a belongs to model after creation

I have a channel mapping model with;

public function channel(): BelongsTo
{
    return $this->belongsTo(Channel::class);
}

After I have created a channel, I need to link it to the channel mapping. With belongsToMany we can do attach, but with just belongsTo do we have a better option than this?

$channel = Channel::firstOrCreate(['name' => $name]);
$channel_mapping->update(['channel_id' => $channel->id]);

I was thinking something like this should exist?

$channel = Channel::firstOrCreate(['name' => $name.'/'.$identifier]);
$channel_mapping->attach($channel);
0 likes
3 replies
booni3's avatar

Thanks. That does not work in this case though.

  • A ChannelMapping BelongsTo a Channel
  • A Channel HasMany ChannelMappings

The channel mapping has already been created, without a related channel channel_id = null

So, the flow is:

  1. Channel Mapping is made without a channel
  2. Channel Mapping is linked to a channel

The proposed solution:

$channel_mapping->channel()->create(['name' => $name]);

will make a new channel but will not link it to the channel mapping as the foreign key is on the channels_mappings table.

Creating the channel and then updating the channel mapping is 2 queriers but I wonder if the best way to do it.

booni3's avatar
booni3
OP
Best Answer
Level 3

This is actually what I was looking for. It does them same thing under the hood I am sure but communicates much better.

$channel = Channel::firstOrCreate(['name' => $name]);
$channel_mapping->channel()->associate($channel)->save();

Please or to participate in this conversation.