Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/Illuminate/Database/Eloquent/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -577,6 +577,24 @@ public function forceFill(array $attributes)
return static::unguarded(fn () => $this->fill($attributes));
}

/**
* Set the foreign key for a relationship to another model.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string|null $relationship
* @return $this
*/
public function for($model, $relationship = null)
{
$relationship ??= Str::camel(class_basename($model));

$foreignKey = $this->{$relationship}()->getForeignKeyName();

$this->forceFill([$foreignKey => $model->getKey()]);

return $this;
}

/**
* Qualify the given column name by the model's table.
*
Expand Down
48 changes: 48 additions & 0 deletions tests/Database/DatabaseEloquentModelTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3178,6 +3178,29 @@ public function testCollectedByAttribute()

$this->assertInstanceOf(CustomEloquentCollection::class, $collection);
}

public function testForCanSetForeignKeysForRelationships()
{
$post = new Post();
$post->id = 123;

$user = new DatabaseEloquentModelTestUser();
$user->id = 456;

$comment = (new Comment());
$this->addMockConnection($comment);

// Set some data so we can make sure "for" isn't clearing it.
$comment->content = 'Hello';

$comment
->for($post)
->for($user, 'user');

$this->assertSame($comment->content, 'Hello');
$this->assertSame($comment->post_id, 123);
$this->assertSame($comment->the_user_id, 456);
}
}

class EloquentTestObserverStub
Expand Down Expand Up @@ -3946,3 +3969,28 @@ class EloquentModelWithCollectedByAttribute extends Model
class CustomEloquentCollection extends Collection
{
}

class DatabaseEloquentModelTestUser extends Model
{
protected $guarded = [];
}

class Post extends Model
{
protected $guarded = [];
}

class Comment extends Model
{
protected $guarded = [];

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

public function user(): BelongsTo
{
return $this->belongsTo(DatabaseEloquentModelTestUser::class, 'the_user_id');
}
}