Laravel Eloquent 查找复合键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28904194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:04:55  来源:igfitidea点击:

Laravel Eloquent find for composite key

phplaraveleloquentlaravel-5

提问by Padarom

I've recently started working with Laravel 5 as a framework. So far everything's been completely straight-forward and it's just great to work with it. Currently however I'm running into some troubles regarding on of my Eloquent models.

我最近开始使用 Laravel 5 作为框架。到目前为止,一切都是完全直接的,使用它真是太好了。然而,目前我在我的 Eloquent 模型上遇到了一些麻烦。

The database table reportshas the following schema:

数据库表reports具有以下架构:

| id | group_id | score | ... |

group_idis a foreign key referencing the groupstable. The primary key of this table is a composite of idand group_id. idis also not auto-increasing, as it's an external id I'm using for easier internal processing.

group_id是引用groups表的外键。此表的主键是一个复合的idgroup_idid也不是自动增加的,因为它是我为了更容易的内部处理而使用的外部 ID。

Each external id can be present for every of my groups once and have a different score for each of them, hence the composite primary key.

每个外部 id 可以为我的每个组出现一次,并且每个组都有不同的分数,因此是复合主键。

When visiting one of my pages, I want to fetch the latest records from my external data source and match them with the corresponding database rows. If they don't exist, I want to create them.

当访问我的一个页面时,我想从我的外部数据源中获取最新的记录并将它们与相应的数据库行进行匹配。如果它们不存在,我想创建它们。

My current code for this route is:

我目前这条路线的代码是:

public function showReports ($id)
{
   $group = Group::findOrFail($id);

   foreach ($group->getLatestReports(20) as $reportElement)
   {
       $report = Report::find($reportElement['id']);
       if (is_null($report))
       {
           $report = new Report;
           // Fill values ...
           $report->save();
       }
   }
}

This obviously doesn't work as anticipated, as it only looks for the id
( ::find($reportElement['id'])), not for the group_id. As usual with my questions, the answer is probably super easy, yet I can't seem to find it right now.

这显然不像预期的那样工作,因为它只查找id
( ::find($reportElement['id'])),而不查找group_id. 和我的问题一样,答案可能非常简单,但我现在似乎找不到。

回答by John Flatness

Model::findonly works with single-column keys. You can pass it an array, but that just makes it look for multiple rows.

Model::find仅适用于单列键。您可以将数组传递给它,但这只会使它查找多行。

You'd need to chain together two where's to make your query:

您需要将两个where's链接在一起进行查询:

$report = Report::where('id', '=', $reportElement['id'])
                ->where('group_id', '=', $group->id)
                ->first();