这不是相关的问题,而且有很多变通方法,但我有一个有趣的观点,问自己以下问题:
假设我有一个User
和一个Comment
模型,通过HasMany
关系连接。
$user = App\User::first(); //his name is John
$user->name = 'George';
$user->comments()->first()->myMethod();
//inside of Comment model
public function myMethod()
{
$userInstanceThatCalledMe = $this->user; //that's loading the record from the database again, but we want the exact same instance, that called the method
//aaaand $user->name would still return 'John' instead of George.
}
我知道我可以将很多东西作为函数参数传递,但是我想知道laravel是否提供了某种方式来通过子方法访问完全相同的父实例。提前谢谢!