我的代码是这样的:
public function getFavoriteStore($param)
{
$num = 20;
$q = $param['q'];
$location = $param['location'];
$result = $this->store_repository->whereHas('favorites', function ($query) use($q, $location) {
$query->select('stores.id', 'stores.name', 'stores.photo','stores.address')
->where('stores.status', '=', 1)
->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Store');
if($location)
$query->where('stores.address', 'like', "%$location%");
if($q) {
$query->where('stores.name', 'like', "%$q%")
->where('stores.address', 'like', "%$q%", 'or');
}
$query->orderBy('favorites.updated_at', 'desc');
})->paginate($num);
return $result;
}
有用
但是,order by 不起作用
此外,上面的查询,我只选择了一些字段。但是当我调试查询时,结果显示所有字段
好像还是有错
有谁能帮助我吗?
我遵循本教程:https ://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence
更新
我最喜欢的模型是这样的:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Favorite extends Model
{
protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
public function favoritable()
{
return $this->morphTo();
}
}
我的商店模型是这样的:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
protected $fillable = ['name', 'address', 'phones', 'address', 'email'];
public function favorites()
{
return $this->morphMany(Favorite::class, 'favoritable');
}
}
收藏表有字段 id、user_id、favoritable_id、favoritable_type
商店表具有字段 id、姓名、地址、电话、地址、电子邮件、照片
store 和 favorite 的关系是 id(stores 表)和 favouritable_id(favorites 表)