[英]How to search some data with foreign key?
在我的網站上我有一些廣告。 我正在嘗試使用外鍵過濾/搜索廣告。 在我的廣告中,我有一些值,例如“名稱”或“city_id”。 City_id 是我所有法國城市的外鍵。
在我的示例中,我想搜索包含城市“Le mans”的廣告。 勒芒是 id = 1。
因此,當用戶寫“Le mans”時,我需要在 City 表中找到 id,而 city_id 就是這個 id 的廣告。
public $query ='';
public $annonces = [];
public function updatedQuery()
{
$words = '%' . $this->query . '%';
if (strlen($this->query) > 1) {
$city = City::select('id')->where('city_name', 'like', $words)->get();
$this->annonces = Annonce::where('name', 'like', $words)
->orWhere('city_id', 'like', $city)->get();
}
}
它不起作用。 怎么了?
嘗試這個:
public $query ='';
public $annonces = [];
public function updatedQuery()
{
$words = '%' . $this->query . '%';
if (strlen($this->query) > 1) {
$cities = City::where('city_name', 'like', $words)->get(['id']); //get() method returns Collection
foreach($cities as $city) {
$this->annonces = Annonce::where('name', 'like', $words)
->orWhere('city_id', 'like', $city)->get();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.