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

标签 php laravel eloquent

美好的一天。 laravel 中使用 with() 函数时是否可以使用别名?举个例子:

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

最佳答案

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

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();

关于php - Laravel Eloquent 在 with() 函数中使用别名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49018265/

相关文章:

php - 使用PHP将长格式数据保存到数据库

php - 在 MySQL/PHP 中从数字 ID 生成字母数字 ID

php - Laravel 和 Blade 的 undefined variable

php - 有什么办法可以解决我的 Eloquent 吗?时间太长

php - 根据选中的复选框插入文本字段内容 php mysql

php - 无法在 PHP 中显示 session 消息?

php - Laravel Eloquent Relationships - 两个不同的送货地址与一个订单模型相关联

mysql - 获取记录 Eloqouent laravel 5 的部分

laravel - HTTP/2 服务器推送 Assets 加载失败 (HTTP2_CLIENT_REFUSED_STREAM)

javascript - 无法在 IOS Safari 上访问对象,但可在桌面 Chrome 上使用