php Laravel Eloquent查找复合键

jhiyze9q  于 2023-09-29  发布在  PHP
关注(0)|答案(3)|浏览(133)

我最近开始使用Laravel 5作为框架。到目前为止,一切都是完全直截了当的,它只是伟大的工作与它。然而,目前我遇到了一些麻烦,关于我的口才模型。
数据库表reports具有以下模式:

| id | group_id | score | ... |

group_id是引用groups表的外键。此表的主键是idgroup_id的组合。id也不是自动增加的,因为它是一个外部ID,我使用它是为了更容易地进行内部处理。
每个外部id可以在我的每个组中出现一次,并且每个组都有不同的分数,因此是复合主键。
当访问我的一个页面时,我想从外部数据源获取最新的记录,并将它们与相应的数据库行进行匹配。如果它们不存在,我想创建它们。
我目前的路线代码是:

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();
       }
   }
}

这显然不能按预期工作,因为它只查找id
::find($reportElement['id'])),不适用于group_id。像往常一样,我的问题,答案可能是超级容易,但我似乎找不到它现在。

ct3nt3jp

ct3nt3jp1#

Model::find只适用于单列键。你可以给它传递一个数组,但这只会让它查找多行。
您需要将两个where链接在一起来进行查询:

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

jobtbby32#

你可以创建一个Trait MutiPrimaryKey,然后扩展getKey和find方法:1)在App\Classes\Database中创建以下文件MultiPrimaryKey.php

<?php

namespace App\Classes\Database;

use Illuminate\Database\Eloquent\Builder;

trait MultiPrimaryKey {

    protected function setKeysForSaveQuery(Builder $query)
    {
        $keys = $this->getKeyName();
        if(!is_array($keys)){
            return parent::setKeysForSaveQuery($query);
        }

        foreach($keys as $keyName){
            $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
        }

        return $query;
    }

    protected function getKeyForSaveQuery($keyName = null)
    {
        if(is_null($keyName)){
            $keyName = $this->getKeyName();
        }

        if (isset($this->original[$keyName])) {
            return $this->original[$keyName];
        }

        return $this->getAttribute($keyName);
    }

    public function getKey()
    {
        $keys = $this->getKeyName();
        if(!is_array($keys)){
            return parent::getKey();
        }

        $pk = [];

        foreach($keys as $keyName){
            $pk[$keyName] = $this->getAttribute($keyName);
        }

        return $pk;
    }

    public function find($id, $columns = ['*'])
    {
        if (is_array($id) || $id instanceof Arrayable) {
            $out = null;
            foreach ($id as $key => $value) {
                //echo "{$key} => {$value} ";
                if ($out == null)
                {
                    $out = $this->where($key, $value);
                }
                else
                {
                    $out = $out->where($key, $value);
                }
            }

            return $out->first($columns);
        }

        return $this->whereKey($id)->first($columns);
    }

}

然后你必须为自定义关系分类:2)在App\Classes\Database中创建以下文件HasMultiPKpage.php

<?php

namespace App\Classes\Database;

use App\Classes\Database\Eloquent\Relations\BelongsToMultiPK;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

trait HasMultiPKRelationships {

    public function belongsTo($related, $foreignKey = null, $ownerKey = null, $relation = null)
    {
        if ($relation === null) {
            $relation = $this->guessBelongsToRelation();
        }

        $instance = $this->newRelatedInstance($related);

        if ($foreignKey === null) {
            $foreignKey = Str::snake($relation) . '_' . $instance->getKeyName();
        }

        $ownerKey = $ownerKey ?: $instance->getKeyName();

        if ( is_array($ownerKey))
        {
            return new BelongsToMultiPK($instance->newQuery(), $this, $foreignKey, $ownerKey, $relation);
        }
        else
        {
            return new BelongsTo($instance->newQuery(), $this, $foreignKey, $ownerKey, $relation);
        }
    }
}

然后你需要自定义的BelongsTo 3)在App\Classes\Database\Eloquent\Relations中创建以下文件BelongsToMultiPK.php

<?php

namespace App\Classes\Database\Eloquent\Relations;

use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Relations\Concerns\SupportsDefaultModels;

class BelongsToMultiPK extends BelongsTo
{

    public function __construct(Builder $query, Model $child, $foreignKey, $ownerKey, $relation)
    {
        parent::__construct($query, $child, $foreignKey, $ownerKey, $relation);
    }

    public function addConstraints()
    {
        if (static::$constraints) {
            // For belongs to relationships, which are essentially the inverse of has one
            // or has many relationships, we need to actually query on the primary key
            // of the related models matching on the foreign key that's on a parent.
            $table = $this->related->getTable();

            if (! is_array($this->ownerKey) )
            {
                $this->query->where($table.'.'.$this->ownerKey, '=', $this->child->{$this->foreignKey});
            }
            else
            {
                foreach ($this->ownerKey as $key)
                {
                    $this->query->where($table.'.'.$key, '=', $this->child->{$this->foreignKey}[$key]);
                }
            }                   
        }
    }
}
bwitn5fc

bwitn5fc3#

我知道这是一个老职位,但这里是我如何处理它使用本地范围查询
1-在Model中:

use Illuminate\Database\Eloquent\Builder;

  public function scopeComposited(Builder $q, $id, $group_id)
  {
    $q->where(["id" => $id, "group_id" => $groupo_id]);
  }

2-要检索模型,请执行以下操作:

Report::composited(1,2)->first();

相关问题