为了账号安全,请及时绑定邮箱和手机立即绑定

查询具有关系的模型字段

查询具有关系的模型字段

PHP
不负相思意 2023-10-21 16:00:30
我有两个模型,用户和枚举器。我想搜索枚举器模型中的某些列及其在用户模型中的关系。这就是我所拥有的;枚举器唯一身份用户名我想编写一个查询来获取同一集合中的 unique_id 和 first_name 。这就是我所拥有的;Enumerator::with(['user' => function($query) {        $query->select('id', 'first_name', 'last_name', 'email'); }])->get(['first_name', 'unique_id']);我该怎么办?
查看完整描述

1 回答

?
LEATH

TA贡献1936条经验 获得超6个赞

如果您想在同一集合中获取多个表列,最好在此处使用联接查询,如下所示


$joinTableName = (new App\User())->getTable();

$fromTableName = (new App\Enumerator())->getTable();

$foreignKey = "enumerators_id"; //user table set foreign key

$localKey = "id";  //enumerators table column local key


$selectColumns = [

    "{$joinTableName}.first_name",

    "{$fromTableName}.unique_id",

];


$a = App\Enumerator::select($selectColumns)

    ->join(

        $joinTableName,

        "{$joinTableName}.{$foreignKey}",

        '=',

        "{$fromTableName}.{$localKey}"

)->get();


dd($a);


查看完整回答
反对 回复 2023-10-21
  • 1 回答
  • 0 关注
  • 71 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信