Select 来自模型的几列和 select 来自其关系的几列 table

Select few columns from Model and select few columns from its relation table

用户模型

class UserModel extends Authenticatable
{

    use Notifiable;

    public $table = 'tbluser';
    public $primaryKey = 'UserID';
    public $timestamps = true;

    public function Role() {
        return $this->hasOne("\App\Models\User\Role\RoleModel", "RoleID", "RoleID");
    }
}

榜样

class RoleModel extends Model
{
    public $table = 'tblrole';
    public $primaryKey = 'RoleID';
    public $timestamps = false;        
}

我的代码如下,它从两个 table 中获取所有列。下面的代码显示了用户 table 的所有列和关系 table - 角色

的所有列
$data = UserModel::with("Role")->get();

我尝试了下面的代码 select 来自 table.

的几列
$data = UserModel
    ::select("UserName", "EmailAddress", "LastName")
    ->with(['Role' => function ($q) {
               $q->select('Role')
            }])
    ->get();

但没有用。它按用户 table 的预期显示三列,但没有来自角色 table 的相关记录的信息。

有什么遗漏吗?

我想你可以试试这个:

$data = UserModel
    ::select("UserName", "EmailAddress", "LastName")
    ->with(['tblrole' => function ($q) {
               $q->select('Role')
            }])
    ->get();

$data = DB::table('tblrole')->select('tblrole.*','tbluser.UserName','tbluser.EmailAddress','tbluser.LastName')
        ->join('tbluser','tbluser.id','=','tblrole.user_id')
        ->get();

希望对您有所帮助。

在您的 with 调用中,您需要 select 来自 Role 模型的主键,以便在查询后检索角色时附加角色。除此之外,select 你想要在闭包中传递给 with 方法的任何其他列:

$data = UserModel::select("UserName", "EmailAddress", "LastName")
    ->with(['Role' => function ($q) {
               $q->select('RoleID', 'Role', 'OtherColumn')
            }])
    ->get();

然后您可以访问用户和角色:

// This will return the first user
$user = $data->first();

// This returns the entire user role model with the selected columns
$role = $user->Role;

// Access Role attributes through the Role Model
$role->Role;

在你的 select(....) of with 添加与 tblUser [=16= 的主键相关的 tblRole table 的外键]. 然后是您要获取的所有其他列的列表。

$data = UserModel
        ::select("UserName", "EmailAddress", "LastName")
        ->with(['Role' => function ($q) {
                   $q->select('RoleID', 'Role')
                }])
        ->get();