谁能分辨出 yii2 中查找和查找一的区别?



我搜索了太多,但仍然不明白上面代码的问题。

$this->_entity_model = $entity_class_name::findOne(['service_request ' => $this->id]);
$t = $entity_class_name::find()->where(['service_request ' => $this->id])->one();

var_dump(isset($this->_entity_model));
var_dump(isset($t));
exit;

如您所见,我有两个查询,一个查询与查找,另一个查询与findOne查询。 问题是:第一个var_dump返回假!第二个是真的? 我不明白这怎么可能?

我得到的第一个查询

"键"service_request"不是列名,不能用作筛选器"。

但第二个是返回好(真实)结果。

$this->id 为 127

更新:

$this->_entity_model = $entity_class_name::find()->where(['service_request' => $this->id])->one();

我现在可以使用它,但我在下面收到错误:为 foreach() 提供的参数无效

我的规则

<?php
namespace appmodels;
use appcomponentsDefaults;
use Yii;
class IndividualTrader extends Entreprise
{ 
const PROCESSING_IFU = 'processing_ifu';
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function rules()
{
return array_merge(parent::rules(),
[
[['service_request','integer']],
[['emplois_generes','ca'], 'required', 'on' => self::SCENARIO_FORM],
[['identifiant_fiscal'], 'required', 'on' => self::PROCESSING_IFU],
[['activite'], 'required', 'on' => self::SCENARIO_ACTIVITY],
[['forme_juridique'], 'default', 'value' => FormeJuridique::PP],
[['emplois_generes'], 'number', 'min' => 0],
[['objet_social'], 'default', 'value' => ''],
//  [['identifiant_fiscal, activite, ville_taxe_professionnelle'], 'required', 'on' => 'fisc'],
[['raison_sociale', 'identifiant_fiscal', 'registre_commerce'], 'unique'],
/*[['has_nationalite'],'safe','on'=>self::SCENARIO_GUIDE],*/
[['registre_commerce_declare', 'date_rc'], 'validateRequiredRegistrationData', 'registration_attribute' => 'has_already_registered_rccm', 'validate_if_value' => 1, 'on' => self::SCENARIO_FORM],
[['telephone'], 'ext.LPNValidator.LPNValidator', 'defaultCountry' => Defaults::COUNTRY_PHONE_CODE, 'on' => self::SCENARIO_CONTACT],
[['prenom_contact', 'nom_contact', 'telephone', 'email'], 'required', 'on' => self::SCENARIO_CONTACT],
[['activite'], 'required', 'on' => self::SCENARIO_FORM],
[['activite_secondaire'], 'compare', 'compareAttribute' => 'activite', 'operator' => '!=', 'message' => Yii::t('app', "{compareAttribute} and {attribute} must not be equal"), 'on' => self::SCENARIO_FORM],
[['trade_name,company_name'], 'safe', 'on' => TradeNameSearch::SCENARIO_TRADE_NAME_SEARCH]
]
);
}
public function init()
{
parent::init();
// initialize attributes with default values
$this->debut_activite = date('d-m-Y');
$this->forme_juridique = FormeJuridique::PP;
$this->date_fin_activite = '31-12';
$this->duree_activite = 99;
}
public function isCitizen()
{
return $this->has_nationalite == 1;
}
public function isForeign()
{
return isset($this->has_nationalite) && $this->has_nationalite == 0;
}
public function hasRegisteredRccm()
{
return $this->has_already_registered_rccm == 0;
}
public function needsToProveAddress()
{
return $this->has_director_different_address == 1;
}
public function getTotalSalaries()
{
return intval($this->emplois_generes) + intval($this->emplois_etrangers);
}
public function isActivityAuthorizationRequired()
{
return isset($this->is_activity_auth_needed) && $this->is_activity_auth_needed == 1;
}
public function isSpecialActivity()
{
return (isset($this->is_activity_auth_needed) && $this->is_activity_auth_needed == 1) || (isset($this->is_import) && $this->is_import == 1);
}
public function hasCNI()
{
return !isset($this->ppCommercant, $this->ppCommercant->type_piece_identite) ? false : ($this->ppCommercant->type_piece_identite == TypePieceIdentite::CNI);
}
public function getPrimaryAddress()
{
$adres = (new Adresse())->findByAttributes(array('entreprise' => $this->id, 'type_adresse' => TypeAdresse::PRIMARY_ADDRESS));
return ($adres->same_address_pp == 0) ? $this->getSecondaryAddress() : $adres;
}
public function getSecondaryAddress()
{
return (new Adresse())->findByAttributes(array('entreprise' => $this->id, 'type_adresse' => TypeAdresse::SECONDARY_ADDRESS));
}
public function getInlinePrimaryAddress()
{
$address = $this->getPrimaryAddress();
return !isset($address) ? '' : $address->getInlineAdresse();
}

public function isPP()
{
return true;
}
public function getRccmViewName()
{
return '_pp';
}
/**
* @param $name
* @param string $operator
* @return CDbCriteria
*/
public function getFullNameCriteria($name, $service_request_alias, $operator = 'AND')
{
$criteria = new CDbCriteria;
//    $criteria->select = "(select CONCAT(pp.nom , CONCAT('|', CONCAT(pp.prenom ,CONCAT('|',ent.nom_commercial)))) from tbl_personne_physique pp, tbl_entreprise ent where pp.id = ent.pp_commercant and ent.service_request = ".$t.".id) as full_name";
$full_name = "(select CONCAT(pp.nom , '|' , pp.prenom, '|' ,ent.nom_commercial) from tbl_personne_physique pp, tbl_entreprise ent where pp.id = ent.pp_commercant and ent.service_request = " . $service_request_alias . ".id)";
$criteria->compare($full_name, $name, true, $operator);
return $criteria;
}
}

企业

use appcomponentsUtils;
use appmodels_baseBaseEntreprise;
use appmodelsPieceJustificative;
use Yii;
use yiidbActiveQuery;
class Entreprise extends BaseEntreprise
{
const WORKFLOW_ID = 'swEntreprise';
const STATUS_DRAFT = 'draft';
const STATUS_DRAFT_CORRECTION = 'draft_correction';
const STATUS_REVISION = 'revision';
const STATUS_REVISION_RETURNED = 'revision_returned';
const STATUS_TRAITEMENT = 'traitement';
// Workflow.
const STATUS_CORRECTION = 'correction';
const STATUS_RETRAIT = 'retrait';
const STATUS_PAIEMENT = 'paiement';
const STATUS_FINISHED = 'finished';
const STATUS_REJECTED = 'rejected';
const STATUS_ROLE_RC = 'role_rc';
const STATUS_ROLE_IF = 'role_if';
const STATUS_ROLE_PATENTE = 'role_patente';
const STATUS_ROLE_CAISSE = 'role_caisse';
const STATUS_VALID = 'valid';
const STATUS_RETURNED = 'returned';
const INSTRUCTION_PENDING = 0;
const INSTRUCTION_VALID = 1;
const INSTRUCTION_REJECTED = 2;
const REGISTRATION_RCCM = "RCCM";
const REGISTRATION_CC = "CC";
const RCCM = "RCCM";
const DGT = "DGT";
const CNSS = "CNSS";
const CARTE = "CARTE";
const ANNONCE = "ANNONCE";
const CNPS = "CNPS";
const DGI_IF = "IFU";
const DGI_TP = "TP";
const AL  ='AL';
const IMPORT = "IMPORT";
// SCENARIOS
const SCENARIO_GUIDE = 'guide';
const SCENARIO_FORM = 'form';
const SCENARIO_CONTACT = 'contact';
const SCENARIO_ACTIVITY_FORM = 'activity_form';
const SCENARIO_ACTIVITY = 'activite';
//DETERMINANTS
const EXPORT = "EXPORT";
const POUVOIR = "POUVOIR";
const MARIE = "MARIE";
const NATIONALITE = "NATIONALITE";
const CNI = "CNI";
const CASIER = "CASIER";
const HONNEUR = "HONNEUR";
const ASSOCIE_PP = "ASSOCIE_PP";
const ASSOCIE_PM = "ASSOCIE_PM";
const AGREMENT = "AGREMENT";
const PLUS = "+";
const MINUS = "-";
const DUREE_ACTIVITE = 99;
const DUREE_IF = 10;
const ONLINE = 1;
const OFFLINE = 2;
const COMMERCANT = 1;
const ENTREPRENANT = 3;
//PARAMS
const SOCIETE = 2;
private static $_role;
public $delai = 0;
/**
* @var $keyword string
* @var $name string
* @var $service string
*/
public $keyword;
public $name;
public $service;
public $inscription;
private $_role_by_status = null;
private $_determinants;
private $_types_pieces;
private $_types_pieces_originaux;
private $_pieces_originaux;
private $_pieces_tobecertified;
private $_formulaires_tobesigned;
private $_is_PP;
private $_deletable;
private $_is_Entreprenant;
public static function model($className = __CLASS__)
{
return parent::model($className);
}
public function rules()
{
return array_merge(parent::rules(), [
[['name', 'service','keyword', 'inscription'], 'safe'],
//array('cc_titulaire, cc_titulaire_rpt, cc_suppleant, cc_suppleant_rpt', 'length', 'max' => 128),
[['devise_capital','activite', 'mode_exploitation', 'journal_annonce'], 'string', 'max' => 500],
[['date_fin_activite'], 'string', 'max' => 20],
[['debut_activite', 'date_rc'], 'date', 'format' => Yii::$app->formatter->dateFormat, 'message' => Yii::t('app', 'The format of {attribute} is invalid.')],
//array('exploitant_rccm', 'length', 'max' => 100),
//array('exploitant_name', 'length', 'max' => 250),
[['debut_activite'], 'date', 'format' => Yii::$app->formatter->dateFormat, 'message' => Yii::t('app', 'The format of {attribute} is invalid.')],
[['email'], 'email'],
]);
}
public static function getCustomStatuslistData()
{
return array(
self::getStatusLbl(self::STATUS_DRAFT) => Yii::t('app', "STATUS_DRAFT"),
self::getStatusLbl(self::STATUS_ROLE_CAISSE) => Yii::t('app', "STATUS_CAISSE"),
self::getStatusLbl(self::STATUS_REVISION) => Yii::t('app', "STATUS_REVISION_CUSTOM"),
self::getStatusLbl(self::STATUS_CORRECTION) => Yii::t('app', "STATUS_CORRECTION"),
self::getStatusLbl(self::STATUS_ROLE_RC) => Yii::t('app', "STATUS_TRAITEMENT_RC"),
self::getStatusLbl(self::STATUS_ROLE_IF) => Yii::t('app', "STATUS_TRAITEMENT_IF"),
self::getStatusLbl(self::STATUS_ROLE_PATENTE) => Yii::t('app', "STATUS_TRAITEMENT_TP"),
self::getStatusLbl(self::STATUS_RETRAIT) => Yii::t('app', "STATUS_RETRAIT_CUSTOM"),
self::getStatusLbl(self::STATUS_FINISHED) => Yii::t('app', "STATUS_FINISHED"),
);
}

感谢您的帮助。

有一个主要区别:

Model::findOne()等于Model::find()->one()

在您的情况下,您应该尝试:

$this->_entity_model = $entity_class_name::findOne(['service_request ' => $this->id]);
$t = $entity_class_name::find()->where(['service_request ' => $this->id])->one();

var_dump(isset($this->_entity_model));
var_dump(isset($t));
exit;

可能发生的情况是,数据库中没有这样的记录。第一个查询看到并返回 null,但第二个查询返回ActiveRecord对象。我看到的一个可能的错误是service_request后的额外空间。尝试删除它,从而进行查询:

$this->_entity_model = $entity_class_name::findOne(['service_request' => $this->id]);

为了更好地理解这些方法的差异,我将举例来比较如何以两种方式从数据库中获取数据:

// find a single customer whose primary key value is 10
$customer = Customer::findOne(10);
// the above code is equivalent to:
$customer = Customer::find()->where(['id' => 10])->one();
// find the customers whose primary key value is 10, 11 or 12.
$customers = Customer::findOne([10, 11, 12]);
// the above code is equivalent to:
$customers = Customer::find()->where(['id' => [10, 11, 12]])->one();
// find the first customer whose age is 30 and whose status is 1
$customer = Customer::findOne(['age' => 30, 'status' => 1]);
// the above code is equivalent to:
$customer = Customer::find()->where(['age' => 30, 'status' => 1])->one();

该方法在框架中的实现如下所示(在 BaseActiveRecord.php 中):

/**
* {@inheritdoc}
* @return static|null ActiveRecord instance matching the condition, or `null` if nothing matches.
*/
public static function findOne($condition)
{
return static::findByCondition($condition)->one();
}

和方法查找按条件:

protected static function findByCondition($condition)
{
$query = static::find();
if (!ArrayHelper::isAssociative($condition)) {
// query by primary key
$primaryKey = static::primaryKey();
if (isset($primaryKey[0])) {
// if condition is scalar, search for a single primary key, if it is array, search for multiple primary key values
$condition = [$primaryKey[0] => is_array($condition) ? array_values($condition) : $condition];
} else {
throw new InvalidConfigException('"' . get_called_class() . '" must have a primary key.');
}
}
return $query->andWhere($condition);
}

请注意,此方法返回return $query->andWhere($condition);

这是一个区别。

为了使两个选项返回相同的内容,需要像这样更改代码:

$this->_entity_model = $entity_class_name::findOne(['service_request' => $this->id]);

但是条件相似的地方和在这种情况下在哪里 $t = $entity_class_name::find()->andWhere(['service_request' => $this->id])->one();

var_dump(isset($this->_entity_model));
var_dump(isset($t));
exit;

PS:"键"service_request"不是列名,不能用作过滤器"。

这是因为列名中设置了空格"service_request "。需要"service_request"

Sergio强调了使用findOne和find()之间的主要区别。

这里的陷阱可能是如果我们在模型"find()"方法上放置了一个前提条件。

即:

/**
* @inheritdoc
* @return commonmodelsUserQuery the active query used by this AR class.
*/
public static function find()
{
$query = new commonmodelsUserQuery(get_called_class());

return $query->where(['user.deleted_by' => 0]);
}

现在,如果我们在控制器或其他地方使用findOne($id)findOne(['id'=>$id]),查询条件将看起来像 'where user.deleted_by = 0 and id = 1',它可能具有也可能没有预期的影响。 正如塞尔吉奥所说...我们可以用find()->andWhere来模仿findOne......但不是find()->where(['id' => $id]).

find()->where(['id' => $id])where 子句中是明确的,并且不允许从请求中的其他地方将其他条件放入其中。

显然是为了在没有 Model::find() 方法中设置前提条件的情况下获得结果......我们只能使用find()->where(['id' => $id])

我在您的模型中看不到 find() 方法,所以这可能根本不是问题......但我不得不提到这个小问题来提醒自己,也许还有其他人......这两者不完全相同:)

最新更新