【问题标题】:Laravel 4 - getting crossing results of tables connected by relationshipLaravel 4 - 获得通过关系连接的表的交叉结果
【发布时间】:2014-09-01 03:51:41
【问题描述】:

使用 Laravel,我创建了一个主表 users,其中包含主键、电子邮件字段和密码字段。然后我创建了其他几个表,例如 physical_detailspersonal_data,它们都带有外键 user_id

现在我在交叉结果时遇到了麻烦。例如,查找具有height = 170(物理详细信息)和同时具有marital_status = married(个人数据)的用户。我尝试对wheres进行分组,但它变得有点复杂,更糟糕的是,结果只带来了主表(用户)的值

【问题讨论】:

  • 看看这个 stackoverflow.com/questions/18599455/eloquent-orm-using-where-in-both-inner-join-tables

标签: php mysql sql laravel


【解决方案1】:

您需要使用Query Builder 来执行join。您可能需要类似于以下代码的内容:

$result = DB::table('users')
            ->distinct() // We most likely don't want duplicate rows
            ->join('physical_details', 'users.id', '=', 'physical_details.user_id')
            ->join('personal_data', 'users.id', '=', 'personal_data.user_id')
            ->select('users.id', 'physical_details.columnX', 'personal_data.columnY')
            ->where('personal_data.marital_status', '=', 'married')
            ->where('physical_details.height', '=', 170)
            ->get();

这里,$result 应该是具有属性idcolumnXcolumnY 的对象数组(选择包含您要查找的信息的任何列)。

我链接到的文档应该可以为您提供更多帮助。

【讨论】:

    【解决方案2】:

    如果表之间的关系是集合。

    $users = User::wherehas('personnal_data',function($q) {
    $q->wheremaritalStatus('Married');
    })->get();
    
    dd($users);
    

    应该有效吗?

    问候,

    【讨论】:

      猜你喜欢
      • 2022-11-23
      • 1970-01-01
      • 2017-05-10
      • 2016-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-07
      • 2015-12-04
      相关资源
      最近更新 更多