Eloquent 查询如何设置表的别名
这是我的模型关联表:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
// 获取下级的徒弟列表
public static function getDisciple($userId){
return self::select('nickname, headimgurl, created_at')->withCount('disciples')->where('parent_id', $userId)->get();
}
// 徒弟的一对多
public function disciples(){
return $this->hasMany('App\Models\User', 'parent_id', 'id');
}
}
我的目的是想获取下级徒弟信息的时候,顺便计算一下下级徒弟的徒弟的数量。我这样写之后,sql报了这个样的错误。
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'nickname, headimgurl, created_at' in 'field list' (SQL: select `nickname, headimgurl, created_at`, (select count(*) from `users` as `laravel_reserved_0` where `users`.`id` = `laravel_reserved_0`.`parent_id`) as `disciples_count` from `users` where `parent_id` = 1)
意思我主表查询的那几个字段不知道归属于哪个表。我本次查询只想查询这几个字段。
如何我能在这次查询中设定主表的别名,那我自己在那几个字段上加上别名,就解决了。
但是问题是我如何才能设定主表的别名?
推荐文章: