【问题标题】:Laravel - pass filter to a modelLaravel - 将过滤器传递给模型
【发布时间】:2019-06-21 01:32:03
【问题描述】:

我需要一些帮助。本质上,有两个表(tblplayers & tblmatches)。并非每个玩家都存在于 tblmatches 中。我的控制器有这个代码:

use App\Model\Players;
use App\Model\Matches;
use Illuminate\Support\Facades\DB;

class PlayersController extends Controller
{
public function index(Request $request) {
$players = Players::select('*');

我想更改上面的 select 语句,使其仅返回也存在于 tblmatches 中的玩家(其中 tblmatches.P1_ID = tblplayers.ID)。

我在下面做错了什么?

$players = Players::addSelect(DB::raw('(SELECT * from tblmatches where (P1_ID = ID))'));

我应该改换型号吗?感谢您的帮助。

【问题讨论】:

    标签: php laravel laravel-5 filter


    【解决方案1】:

    一对多关系(详情here)添加到您的玩家模型(也可能添加到您的 Matches 模型)

    public function matches()
    {
        return $this->hasMany('App\Model\Matches');
    }
    

    还有query它由

    $players = Players::has('matches')->get();
    

    【讨论】:

    • 不错!谢谢你,先生。像魅力一样工作
    【解决方案2】:

    您绝对应该在两个表之间设置relationship。它会使这样的案件更容易处理。

    但是,您要查找的实际上是 WHERE EXISTS。所以,像下面这样的东西应该可以解决问题。

    $players = Players::whereExists(function ($query) {
            $query->select(DB::raw(1))
                ->from('tblmatches')
                ->whereRaw('tblmatches.player_id = tblplayers.id');
        })
        ->get();
    

    我假设您在whereRaw() 中有这两个字段,但您应该相应地更改它。

    whereRaw('tblmatches.player_id = tblplayers.id');
    

    但是,一定要看看关系:)

    【讨论】:

    • 不幸的是,该解决方案引发了错误“BadMethodCallException Method Illuminate\Database\Eloquent\Collection::addSelect 不存在。”
    • 根据错误消息,感觉就像您将addSelect() 链接到结果(这是一个集合)。你不应该那样做。 $players 本身将包含您可以使用的 Players 模型的集合。它应该工作:)
    • 顺便说一下,这是一个可以使用的example
    【解决方案3】:

    检查此链接。 https://laravel.com/docs/5.7/queries

     protected $table = 'tblplayers';
       public function fetchPlayers ($data) {
        $players =  DB::table($this->table)
       // you can filter it by Boolean expression using where 
        ->where('status', '<>', 1)
       // you can group by
        ->groupBy('status')
        ->get();
        return $players;
      }
    

    【讨论】:

      猜你喜欢
      • 2013-08-17
      • 2014-10-19
      • 1970-01-01
      • 2013-02-09
      • 2022-08-02
      • 2016-12-11
      • 2015-03-22
      • 2016-04-17
      • 2021-12-02
      相关资源
      最近更新 更多