2017-02-25 52 views
1

我的代碼是這樣的:如何通過查詢關係存在來選擇一些字段和順序? 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(收藏表)

+0

我會使用Laravel調試欄來查看生成的實際SQL並從那裏開始。 –

+0

商店和收藏夾之間的關係是什麼? –

回答

1

whereHas()僅用於檢查的關係的存在的話,你必須使用join()訂購與相關表中的結果

$query = $this->store_repository 
    ->join('favorites', function ($join) { 
     $join->on('stores.id', '=', 'favorites.favoritable_id') 
      ->where('favorites.favoritable_type', 'like', 'App\\\Models\\\Store'); 
    }) 
    ->where('stores.status', '=', 1) 
    ->select('stores.id', 'stores.name', 'stores.photo','stores.address'); 

if($location) 
    $query->where('stores.address', 'like', "%$location%"); 

if($q) { 
    $query->where('stores.name', 'like', "%$q%") 
     ->where('stores.address', 'like', "%$q%", 'or'); 
} 

$result = $query->orderBy('favorites.updated_at', 'desc')->paginate($num); 

我沒有測試過,但我敢確定它會工作。

+0

太好了。有用。謝謝 –

+0

但是,我稍微修改了你的代碼。像這樣:'if($ location) $ query = $ query-> where('stores.address','like',「%$ location%」); if($ q){ $ query = $ query-> where('stores.name','like',「%$ q%」) - > where('stores.address','like', 「%$ q%」,「或」); } $ query = $ query-> orderBy('favorites.updated_at','desc') - > paginate($ num);'。因爲存在錯誤:'類照明\數據庫\ Eloquent \ Builder的對象無法轉換爲字符串' –

+0

正如我在前面的問題中指出的那樣,您不必爲每個'where'存儲'$ query'變量,條款。你能否再次檢查更新後的答案。 –