2017-02-25 68 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'变量,条款。你能否再次检查更新后的答案。 –