从方法内部访问父类调用关系方法的某个实例

时间:2017-08-13 14:53:25

标签: relationship laravel-5.4

这不是相关的问题,而且有很多变通方法,但我有一个有趣的观点,问自己以下问题: 假设我有一个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是否提供了某种方式来通过子方法访问完全相同的父实例。提前谢谢!

0 个答案:

没有答案