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

how to use queries on 2 relationships in laravel

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

例如,显示日期为 4/11/2019 的房间和 london

中的城市

控制器:

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

$测试结果:

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

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 ▶}
  ]
}

你可以这样做,

$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

我希望 table 中的日期格式与 m/d/Y 相同,否则您必须按照以下步骤操作。

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

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

Note: Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. If, however, the year is given in a two digit format and the separator is a dash (-, the date string is parsed as y-m-d.

编辑

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

最重要的是日期字段和城市应该使用相等的条件而不是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();

也许你可以试试

$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();

你可以试试这个:

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

如果您只需要 属性 的详细信息,而不需要关系数据,那么您可以尝试:

whereHas 

如果要根据实体关系的条件过滤实体,则需要 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'