как использовать запросы на 2 отношения в laravel - PullRequest
1 голос
/ 11 апреля 2019

У меня есть модель с 2 отношениями.Я хочу добавить, где условие для каждого отношения.

Например, покажите мне комнату с датой 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 ▶}
  ]
}

Ответы [ 5 ]

2 голосов
/ 11 апреля 2019

Вы можете сделать что-то вроде этого,

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

См. Документацию, как его использовать здесь .

Я надеюсь, что ваш формат даты в таблице такой как m/d/Y если нет, следуйте приведенным ниже инструкциям.

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

Вы можете использовать переменную $date вместо 4/11/2019.

Примечание. Даты в м / мФорматы d / y или dmy устраняются, рассматривая разделитель между различными компонентами: если разделитель является косой чертой (/), то предполагается, что используется американский m / d / y;тогда как, если разделителем является тире (-) или точка (.), то подразумевается европейский формат dmy.Однако, если год указан в двузначном формате, а разделителем является тире (-, строка даты анализируется как ymd.

РЕДАКТИРОВАТЬ

$property = Property::with(['dates' => function ($query) {
    $query->where('datefield', 'like', '4/11/2019');
}])->get();
1 голос
/ 16 апреля 2019

Если вы хотите отфильтровать сущности по условиям их отношений, вам нужно whereHas() (см. Запрос наличия отношения ):

$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() (см. Ограничение активных нагрузок ):

$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'.

1 голос
/ 15 апреля 2019

Может быть, вы можете попробовать

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

и вам не нужно LIKE. См. документацию , я не говорю, что 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();
0 голосов
/ 16 апреля 2019

Вы можете попробовать это:

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

Если вам нужны только детали свойства, а не данные отношения, то вы можете попробовать:

whereHas 
0 голосов
/ 15 апреля 2019

Наиболее важным является поле даты и город должны использовать равное условие, а не 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();
...