从数据透视表中选择所有行

3

我在Slim框架上使用Eloquent选择数据透视表的行时遇到了一些麻烦。我有以下关系:

tb_bet(id,...)
tb_fixture(id,...)
tb_bet_fixture(bet_id,fixture_id,status)

模型

Bet.php:

use \Illuminate\Database\Eloquent\Model;

class Bet extends Model {

    protected $connection = 'client';
    protected $table = 'tb_bet';
    public $timestamps = false;

    public function fixtures() {
        return $this->belongsToMany('Fixture')->withPivot('status');
    }
}

Fixture.php:

use \Illuminate\Database\Eloquent\Model;

    class Fixture extends Model {

        protected $connection = 'client';
        protected $table = 'tb_fixture';
        public $timestamps = false;

        public function bets() {
            return $this->belongsToMany('Bet')->withPivot('status');
        }
    }

我能够查询某一场比赛的所有投注以及所有投注中的所有比赛,但是我真正需要的是这样做:select * from tb_bet_fixture where bet_id = 1。因此,我有了给定投注的所有比赛状态列表。就像这样:

bet:{
  'id': 1,
  'pivot': [
      {bet_id: 1, fixture_id: 2, status: true},
      {bet_id: 1, fixture_id: 3, status: false},
      {bet_id: 1, fixture_id: 4, status: true}
  ]
}

我想使用原始查询,但是每当我尝试在我的控制器上声明use Illuminate\Database\Capsule\Manager as DB;并使用$users = DB::select('select * from tb_users');作为测试时,我会收到一个Database [default] not configured.错误,并且我不知道如何访问包含当前连接的'$capsule'变量(是的,我使用多个连接到不同的数据库),并且该变量被定义在中间件中。无论如何,我会感激任何帮助。

更新了我的答案。 - aimme
1个回答

2

选项1:创建模型

如果我要使用数据透视表作为模型,我会为数据透视表创建一个模型。这样,您就可以直接查询该表。像这样。

use \Illuminate\Database\Eloquent\Model;
use App\Bet;

class BetFixture extends Model 
{
    protected $table =‘tb_bet_fixture’;

    public function bets() 
    {
        return $this->hasMany(Bet::class);
    }
} 

这将使查询变得更加简单明了,就像直接从数据透视表中选择一样。
select * from tb_bet_fixture where bet_id = 1. 

选项2:使用赛事下注查询

如果您想通过赛事下注查询来选择特定的比赛,请按以下方式进行查询。

Fixture::with(‘bets’ => function($query) use ($betId) {
    $query->where(‘tb_bet_fixture.bet_id,$betId);
});

1
我刚看到答案,但是模型方法才是昨天解决我的问题的方法。感谢您的帮助。 - Guilherme Ramalho
1
创建一个数据透视表模型,正是我需要听到的。谢谢! - Joel

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接