简体   繁体   中英

how to use queries on 2 relationships in laravel

I have model with 2 relationships. I want to add where condition on each relationship.

For example show me a room that date is 4/11/2019 and the city in london

Controller:

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

$test result:

It may be a bit long but I expanded whole result so you can check the relations as dates is in a pivot relation :

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

You can do something like this,

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

Refer documentation how to use it here .

I hope your date format in the table is as m/d/Y if not you have to follow below steps.

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

You can use $date variable in place of 4/11/2019 .

Note: Dates in the m/d/y or dmy 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 dmy 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 ymd.

EDIT

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

May be you can try

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

and you do not need LIKE . See documentation , I am not saying LIKE will not work, but using a = or whereDate will be more accurate.

Can you try

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

or

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

If you want to filter the entities by conditions on their relations, then you need whereHas() (see 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();

If you also want to filter the returned relations by the same condition, then you can do it within with() (see 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();

You only need to do that for dates , since there can be only one details relation, which is already constrained to 'london' .

Most important thing is Date field and City should be use equal condition not like condition.

Notes : You should check your date format for proper data output.

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

You can also use whereDate() function to compare date field.

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

You can try this :

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

If you need details of property only, not the relation data, then you can try for :

whereHas 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM