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条)

报告相同问题?