我的代碼是這樣的:如何通過查詢關係存在來選擇一些字段和順序? Laravel 5.3
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;
}
它的工作原理
但是,爲了通過不起作用
另外,上面的查詢,我只選擇一些領域。但是,當我調試查詢,結果顯示所有領域
看來還是有錯
是否有任何人誰可以幫我?
我按照這個教程:https://laravel.com/docs/5.3/eloquent-relationships#querying-relationship-existence
UPDATE
我最喜歡的模式是這樣的:
<?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');
}
}
收藏桌子有領域我d,USER_ID,favoritable_id,favoritable_type
店表有字段ID,姓名,地址,電話,ADDRES,電子郵件,照片
商店和喜愛的之間的關係是ID(存儲表)和favoritable_id(收藏表)
我會使用Laravel調試欄來查看生成的實際SQL並從那裏開始。 –
商店和收藏夾之間的關係是什麼? –