Laravel Eloquent 在 with() 函数中使用别名

Luk*_*ngi 13 php laravel eloquent

再会。在 Laravel 中使用 with() 函数时是否可以使用别名?例如:

$posts = Post::where(/*condition*/)->with('user as friend')->get();
Run Code Online (Sandbox Code Playgroud)

Why*_*ala 8

简短的回答是否定的,但您可以定义您与要使用的别名的关系并急切加载它。

class Post extends Model
    public function user(){
        return $this->belongsTo(User::class);
    }

    public function friend(){
        return $this->user()
    }
}

$posts = Post::where(/*condition*/)->with('friend')->get();
Run Code Online (Sandbox Code Playgroud)