【发布时间】:2017-02-25 04:11:11
【问题描述】:
我的代码是这样的:
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');
}
}
Favorites 表有字段 id、user_id、favoritable_id、favoritable_type
Stores 表包含字段 id、姓名、地址、电话、地址、电子邮件、照片
store和favorite的关系是id(stores表)和favoritable_id(favorites表)
【问题讨论】:
-
我会使用 Laravel 调试栏查看生成的实际 SQL 并从那里开始。
-
店铺和收藏有什么关系?
标签: php laravel laravel-5.3 laravel-eloquent