如何在laravel中使用2个关系的查询

时间:2019-04-11 12:34:51

标签: php laravel multidimensional-array eloquent eloquent--relationship

我有2个关系的模型。我想在每个关系上添加条件。

例如,给我显示一个房间,日期为4/11/2019,城市为london

控制器:

    $test = Property::with('dates','details')->get();

$ test结果:

可能有点长,但是我扩展了整个结果,因此您可以检查关系,因为日期处于关键关系中:

Collection {#1708 ▼


 #items: array:2 [▼
    0 => Property {#1457 ▼
      #guarded: []
      #connection: "mysql"
      #table: "properties"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:8 [▶]
      #original: array:8 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:2 [▼
        "dates" => Collection {#1607 ▼
          #items: array:1 [▼
            0 => Date {#1600 ▼
              #connection: "mysql"
              #table: "dates"
              #primaryKey: "id"
              #keyType: "int"
              +incrementing: true
              #with: []
              #withCount: []
              #perPage: 15
              +exists: true
              +wasRecentlyCreated: false
              #attributes: array:7 [▶]
              #original: array:9 [▶]
              #changes: []
              #casts: []
              #dates: []
              #dateFormat: null
              #appends: []
              #dispatchesEvents: []
              #observables: []
              #relations: array:1 [▼
                "pivot" => Pivot {#1602 ▼
                  +incrementing: false
                  #guarded: []
                  #connection: null
                  #table: "date_property"
                  #primaryKey: "id"
                  #keyType: "int"
                  #with: []
                  #withCount: []
                  #perPage: 15
                  +exists: true
                  +wasRecentlyCreated: false
                  #attributes: array:2 [▶]
                  #original: array:2 [▶]
                  #changes: []
                  #casts: []
                  #dates: []
                  #dateFormat: null
                  #appends: []
                  #dispatchesEvents: []
                  #observables: []
                  #relations: []
                  #touches: []
                  +timestamps: false
                  #hidden: []
                  #visible: []
                  #fillable: []
                  +pivotParent: Property {#1461 ▶}
                  #foreignKey: "property_id"
                  #relatedKey: "date_id"
                }
              ]
              #touches: []
              +timestamps: true
              #hidden: []
              #visible: []
              #fillable: []
              #guarded: array:1 [▶]
            }
          ]
        }
        "details" => PropertyDetail {#1702 ▼
          #fillable: array:7 [▶]
          #connection: "mysql"
          #table: "property_details"
          #primaryKey: "id"
          #keyType: "int"
          +incrementing: true
          #with: []
          #withCount: []
          #perPage: 15
          +exists: true
          +wasRecentlyCreated: false
          #attributes: array:10 [▶]
          #original: array:10 [▼
            "id" => 52
            "property_id" => 65
            "state" => "london"
            "city" => "london"
            "address" => "5"
            "post_code" => 5
            "placearea" => 1
            "telephone" => 5
            "created_at" => "2019-04-09 21:03:10"
            "updated_at" => "2019-04-09 21:03:10"
          ]
          #changes: []
          #casts: []
          #dates: []
          #dateFormat: null
          #appends: []
          #dispatchesEvents: []
          #observables: []
          #relations: []
          #touches: []
          +timestamps: true
          #hidden: []
          #visible: []
          #guarded: array:1 [▶]
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
    }
    1 => Property {#1458 ▶}
  ]
}

5 个答案:

答案 0 :(得分:2)

您可以这样做,

$data = Property::with(['dates' => function ($query) {
    $query->where('datefield', 'like', '4/11/2019'); // datefield I ain't saw in your output, you can replace it 
}],['details' => function ($query) {
    $query->where('city', 'like', 'london');
}])->get();
dd($data);

请参阅文档here

我希望表中的日期格式为m/d/Y,如果不必,请按照以下步骤操作。

$date = date("Y-m-d",strtotime(str_replace("/","-",$yourdate)));

您可以使用$date变量代替4/11/2019

  

注意:通过查看,可以消除m / d / y或d-m-y格式的日期的歧义。   在各个组件之间的分隔符处:如果分隔符是   斜线(/),则假定为美国m / d / y;而如果   分隔符是破折号(-)或点(。),然后是欧洲d-m-y格式   假设。但是,如果年份以两位数格式给出,并且   分隔符为破折号(-,日期字符串被解析为y-m-d。

编辑

$property = Property::with(['dates' => function ($query) {
    $query->where('datefield', 'like', '4/11/2019');
}])->get();

答案 1 :(得分:1)

最重要的是日期字段和城市应该使用相等的条件,而不是like条件。

注意事项::您应该检查日期格式以获取正确的数据输出。

$data = Property::with(['dates' => function ($query) {
            $query->where('your_date_field', '=', '4/11/2019');
        }],['details' => function ($query) {
            $query->where('city', '=', 'london');
        }])->get();

您还可以使用whereDate()函数比较日期字段。

$data = Property::with(['dates' => function ($query) {
                $query->whereDate('your_date_field', '4/11/2019');
            }],['details' => function ($query) {
                $query->where('city', '=', 'london');
            }])->get();

答案 2 :(得分:1)

也许您可以尝试

$property = Property::with(['dates' => function ($query) {
    $query->whereDate('datefield', '4/11/2019');
}])->get();

,您不需要LIKE。请参见documentation,我并不是说LIKE无效,但是使用=whereDate会更准确。

您可以尝试

$data = Property::with(['dates' => function ($query) {
            $query->whereDate('your_date_field', '=', '4/11/2019');
        }],['details' => function ($query) {
            $query->where('city', 'london');
        }])->get();

$data = Property::whereHas('dates', function($query){
    $query->where('your_date_field', '4/11/2019');
})->whereHas('city', function($query){
    $query->where('city', 'london');
})->get();

答案 3 :(得分:1)

如果要按实体之间的关系条件过滤实体,则需要whereHas()(请参见Querying Relationship Existence):

$searchDate = '2019-04-11';
$searchCity = 'london';

$test = Property::with('dates','details')
        ->whereHas('dates', function($query) use($searchDate) {
            $query->where('date', $searchDate);
        })
        ->whereHas('details', function($query) use($searchCity) {
            $query->where('city', $searchCity);
        })
        ->get();

如果您还希望按相同条件过滤返回的关系,则可以在with()(请参阅Constraining Eager Loads)内进行操作:

$test = Property::with(['details', 'dates' => function($query) use($searchDate) {
            $query->where('date', $searchDate);
        }])
        ->whereHas('dates', function($query) use($searchDate) {
            $query->where('date', $searchDate);
        })
        ->whereHas('details', function($query) use($searchCity) {
            $query->where('city', $searchCity);
        })
        ->get();

您只需要对dates进行此操作,因为只能存在一个details关系,该关系已被约束为'london'

答案 4 :(得分:0)

您可以尝试以下方法:

$data = Property::with([
    'dates' => function ($query) {
        $query->whereDate('your_date_field', 'formatted_date');
    },
    'details' => function ($query) {
        $query->where('city', '=', 'london');
    }
])->get();

如果仅需要属性的详细信息,而无需关系数据,则可以尝试:

whereHas