douhuiyan2772 2014-07-14 05:09
浏览 34
已采纳

Laravel 4.1 Eloquent使用“where”和“with”来过滤相关的MySQL表

Attempting to emulate a LEFT JOIN using Eloquent and receiving an error. Basically, I am trying to get Users with addresses, but only of a certain type.

This code does not work, but I think you will get the gist:

$user = User::with('addresses', 'cards')->where(function($query) {
    $query->where('address.type', '=', 'shipping');
})->find(Auth::user()->id);

If I leave off the where it works fine, but more addresses returned than I need/want.

How can I make it so I only get addresses with a type = 'shipping'? I might want to do the same thing with cards as well. If there are no shipping addresses, I still want everything else.

I was trying to use Eloquent vs Fluent/DB (which I did make work), but just can't figure it out.

Follow-up: Depending on what version of PHP you have, you may need to do array(load array) vs. [load array]. Dev and Prod are not always the same.

  • 写回答

2条回答 默认 最新

  • doxqszx09742 2014-07-14 05:26
    关注

    You can try something like

    $user = Auth::user();
    $user->load(['cards', 'addresses' => function($q) {
        $q->where('type', 'shipping');
    }]);
    

    Eager Loading - Constraints / Lazy Eager Loading

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波