【问题标题】:Nested Query in laravellaravel 中的嵌套查询
【发布时间】:2016-04-27 06:15:33
【问题描述】:

我有两张桌子:

表 1:tbluser

ID 姓名
1 .......... 名称1
2 .......... 名称2
3 .......... 姓名3

另一个链接 tbluser 和 tblrole 的表

表 2:tbllinkuserrole
userid..........roleid
1 ....2
1 .... 2
1 .... 2
2 .... 2
3 .......... 1

我想从 tbllinkuserrole 获取 tbluser.Name 和用户角色到一个表中:根据从 tbllinkuser 角色获取的角色,单个表行(用户记录)可以在“角色”列中包含多行。一个用户可以有多个角色。 你能帮帮我吗...

【问题讨论】:

  • 你使用哪个 Laravel 版本?

标签: mysql laravel


【解决方案1】:

Laravel 有模型(Eloquent),模型类中有一些易于用户从表中获取数据的函数。 (这适用于 Laravel 5.2)

Laravel 中包含的 Eloquent ORM 提供了一个漂亮、简单的 ActiveRecord 实现来处理你的数据库。每个数据库表都有一个相应的“模型”,用于与该表进行交互。模型允许您查询表中的数据,以及将新记录插入表中。 https://laravel.com/docs/5.2/eloquent

首先,您需要一个用户模型 (php artisan make:model User)。您需要将用户模式链接到正确的表格。

//File: /laravel/app/User.php
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    protected $table = 'tbluser';

    public function userRoles() {
        //Get the table data with the user roles
        $this->hasMany('App\UserRoles', 'user_id', 'id');
        //First argument gets the UserRoles Modal
        //Second argument get the UserRoles column 'user_id'
        //Third argument get the User table - column id
}

//File: /laravel/app/UserRoles.php
use Illuminate\Database\Eloquent\Model;
class UserRoles extends Model
{
    protected $table = 'tbllinkuserrole';

    public function rank() {
        //Get the table data with role
        $this->hasOne('App\Roles', 'id', 'role_id');
        //First argument gets the Roles Modal (table)
        //Second argument get the Roles column 'id'
        //Third argument get the UserRoles modal (table) - column role_id
}

//File: /laravel/app/Roles.php
use Illuminate\Database\Eloquent\Model;
class Roles extends Model
{
    protected $table = 'tblroles';
}

现在,如果您调用Auth::user()->userRoles,您将获得一个数组,其中包含表中链接到当前用户的所有行。

当您运行此程序时,您会转储所有用户排名数据。

foreach(Auth::user()->userRoles as $userrole) {
    {{ dump($userrole) }}
    {{ dump($userrole->rank) }}
}

我希望这对你有用!

更多信息请访问https://laravel.com/docs/5.2/eloquent

【讨论】:

    【解决方案2】:

    试试这个

    SELECT tbllinkuserrole.userid, tbllinkuserrole.roleid, tbluser.name
    FROM tbllinkuserrole, tbluser
    WHERE tbllinkuserrole.userid = tbluser.id 
    

    【讨论】:

      【解决方案3】:

      mysql 获取行值作为列,

      SELECT U.id, U.Name, MAX(CASE WHEN R.roleid = 1 THEN R.roleid END) role_1, MAX(CASE WHEN R.roleid = 2 THEN R.roleid END) role_2 from table_c AS U LEFT JOIN table_b AS R on (U.id = R.userid) WHERE 1 GROUP BY U.id
      

      【讨论】:

      • 如何在表格中显示单个用户行,在“角色”列内创建多行。因为一个用户可以拥有多个角色..我想在列 Role 下的一行中显示所有角色。
      • 我已经更新了我的答案,你想要每列中的每个角色 ID
      猜你喜欢
      • 2020-01-23
      • 2015-06-27
      • 2018-06-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 2019-03-30
      相关资源
      最近更新 更多