Php 外键为两列的Laravel关系
我有一个应用程序,其中我在一个名为“games”的表中有一些数据,看起来像这样:Php 外键为两列的Laravel关系,php,laravel,laravel-5,eloquent,laravel-eloquent,Php,Laravel,Laravel 5,Eloquent,Laravel Eloquent,我有一个应用程序,其中我在一个名为“games”的表中有一些数据,看起来像这样: # games +----+---------+--------+--------+ | id | name | dataId | parent | +----+---------+--------+--------+ | 1 | Team1 | 444 | null | +----+---------+--------+--------+ | 2 | Team2 | 445 |
# games
+----+---------+--------+--------+
| id | name | dataId | parent |
+----+---------+--------+--------+
| 1 | Team1 | 444 | null |
+----+---------+--------+--------+
| 2 | Team2 | 445 | null |
+----+---------+--------+--------+
| 3 | Team1.1 | 445 | 1 |
+----+---------+--------+--------+
| 4 | Team2.1 | 445 | 2 |
+----+---------+--------+--------+
| 5 | Team2.2 | 445 | 2 |
+----+---------+--------+--------+
| 6 | Team3 | 446 | null |
+----+---------+--------+--------+
| 7 | Team4 | 447 | null |
+----+---------+--------+--------+
正如您所看到的,记录可以有一个指向表中主记录的父记录
我还有另一张名为“fixtures”的表,该表如下所示:
# fixtures
+----+--------+--------+-------+
| id | homeId | awayId | score |
+----+--------+--------+-------+
| 1 | 444 | 445 | 0 |
+----+--------+--------+-------+
| 2 | 445 | 446 | 0 |
+----+--------+--------+-------+
| 3 | 446 | 447 | 0 |
+----+--------+--------+-------+
// For Home:
WHERE fixtures.homeId = games.dataId AND games.parent = null
// And another for Away:
WHERE fixtures.awayId = games.dataId AND games.parent = null
因此,我要做的是使用Eloquent将两个表连接起来,如下所示:
# fixtures
+----+--------+--------+-------+
| id | homeId | awayId | score |
+----+--------+--------+-------+
| 1 | 444 | 445 | 0 |
+----+--------+--------+-------+
| 2 | 445 | 446 | 0 |
+----+--------+--------+-------+
| 3 | 446 | 447 | 0 |
+----+--------+--------+-------+
// For Home:
WHERE fixtures.homeId = games.dataId AND games.parent = null
// And another for Away:
WHERE fixtures.awayId = games.dataId AND games.parent = null
我想我可以使用OneToMany,但我只能指定一个外键
这在拉维尔可能吗?如果是,如何返回?您可以尝试返回具有正确属性集的实例。由于原始函数belongToMany也返回此类的对象
编辑:一些谷歌搜索给了我这个答案(),这个答案使用了一个特征。可以在上找到代码。对第一个查询使用此查询,对第二个查询更改字段名
$result = DB::table('fixtures')
->join('games', 'fixtures.homeId', '=', 'games.dataId')
->select(DB::raw('fixtures.id','fixtures.homeId','fixtures.awayId','games.name','games.id'))
->where('games.parent', null)
->get();
return($result);