【问题标题】:How to get data from both tables in manytomany relationship?如何从多对多关系的两个表中获取数据?
【发布时间】:2015-02-18 10:48:31
【问题描述】:

我有用户和电子邮件表。每个用户有很多电子邮件,每个电子邮件可以有很多用户。我有 users_email 数据透视表来查询数据。

 $all=User::with('emails')->get();

上述查询工作正常,但现在我想使用 WHERE 子句来获取具有特定电子邮件的特定用户。到目前为止我已经尝试过了,但结果是不可预测的。

    $all=User::with(array('emails'=>function($query){
    $query->where('users.Id','=','78')->where('emails.Id','=','124');
    }))->first();

我希望运行这个查询,但实际上它没有

select * from users inner join users_email on
users.Id=user_email.Uid inner join email on
email.Id=user_email.email_id where email.Id=78
AND users.Id=45

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    将闭包传递给with() 将过滤急切加载的模型,但不会更改返回的User 模型。为此你需要whereHas():

    $all = User::with('emails')->whereHas('emails', function($query){
        $query->where('email_id','=','124');
    })->get();
    

    【讨论】:

    • 列未找到 emails.Id :(
    • emails 中有 Id 列吗?
    • 是的,这是我表的主键
    • 现在工作正常 N 我将查询更改为 $all = User::with('emails')->whereHas('emails', function($query){ $query->where( 'users_email.email_id','=','124')->where('users_email.Uid','=','78'); // 或任何其他 where 条件 })->first(); $all->email;//打印用户表中的email Id,但不打印email表中的消息 $all->message;
    • 如果您只想要通过 id 发送的电子邮件和消息,为什么不使用 $email = Email::find(124); echo $email->message;
    【解决方案2】:

    您可以为此使用普通的内部连接。此查询应为您提供用户 ID 78 的所有电子邮件地址:

    select * 
    from users, user_email, email
    where users.id=user_email.email_id and usermail.email_id=email.id
    and users.id=45
    

    【讨论】:

    • 我不想用简单的东西,即使我可以用简单的内部连接来做......!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多