【发布时间】:2019-03-30 17:45:37
【问题描述】:
大家好,我需要查询一段深厚的关系......
我的store 模特
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
protected $table = 'stores';
public function address(){
return $this->morphOne('App\Model\Address', 'addressable');
}
}
我的Address 模特
class Address extends Model
{
protected $table = 'address';
protected $fillable = [
'province_id',
'city_id',
'brgy_id',
'street_lot_blk',
'longitude',
'latitude'
];
public function addressable(){
return $this->morphTo();
}
public function province(){
return $this->hasOne('App\Model\Province', 'id', 'province_id');
}
public function city(){
return $this->hasOne('App\Model\City', 'id', 'city_id');
}
public function brgy(){
return $this->hasOne('App\Model\Brgy', 'id', 'brgy_id');
}
}
我的province 模特
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Province extends Model
{
protected $table = 'refprovince';
}
我的查询
$request = app()->make('request');
return response()->json([
'stores' => Store::where('name', 'LIKE', '%'. $request->name . '%')
->with(['address.province', 'address.city', 'address.brgy'])
->take(10)->get()
]);
result 见附图
问题是如果用户输入商店的名称,它只会返回商店的名称,如果用户输入“Camarines”,它只会返回在省内有“Camarines”字样的商店。
我的代码看起来像这样......但它不起作用。
$results = Store::where('name', 'LIKE', '%'. $request->name . '%')
->with(['address.province' => function($query) use ($request) {
$query->where('provDesc', 'LIKE', '%'. $request->name . '%');
}])
->take(10)->get();
return response()->json([
'stores' => $results
]);
我不知道这是否可能,请告诉我,以便我可以重新构建我的数据库。 TY
更新:仍然无法使用这些代码。
$request = app()->make('request');
$stores = Store::where('name', 'LIKE', "%{$request->name}%")
->orWhereHas('address.province', function ($query) use ($request) {
$query->where('provDesc', 'LIKE', "%{$request->name}%");
})
->with(['address.province', 'address.city', 'address.brgy'])
->get();
【问题讨论】:
-
那么您想要名称匹配的商店或 provDesc 匹配的商店?
-
是的...但它不起作用。这可能吗?
标签: laravel relationship