【问题标题】:laravel query model with condtion and related model with another condition in same query具有条件的laravel查询模型和具有同一查询中另一个条件的相关模型
【发布时间】:2015-03-04 15:28:07
【问题描述】:

这是我想要做的:

$results = Community::with('floorplan')
                    ->where('communities.city', '=', 'Miami')
                    ->where('floorplans.number_of_bedrooms', '=', $bedrooms)
                    ->get();

我有两个模型,Community 和 Floorplan。关系是社区有许多平面图。关系设置正确。

如何从迈阿密获得卧室数量相同的所有社区?城市在社区表上。卧室数量在平面图表上。我需要原始查询和联接吗?

【问题讨论】:

    标签: laravel model eloquent


    【解决方案1】:
    $query = Community::with('floorplan')->where('city', 'Miami');
    
    $query->whereHas('floorplan', function($query) use ($bedrooms)
    {
        $query->where('number_of_bedrooms', $bedrooms);
    });
    
    $results = $query->get();
    

    如果您愿意,当然可以将其全部链接起来。为了清楚起见,只是在这里分开。

    【讨论】:

    • 太棒了。然而,使用 mysql 似乎更容易/更简单。
    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 2018-03-01
    • 1970-01-01
    • 2011-12-02
    • 2016-10-12
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多