简体   繁体   English

升级到Yii2,ORM不起作用

[英]Upgrading to Yii2, ORM not functional

I'm upgrading a big project form Yii1 to Yii2. 我正在将一个大项目从Yii1升级到Yii2。 I'm having some problems regarding to ORM. 关于ORM,我遇到了一些问题。

I have several relation declared in the following fashion(basically a copy-paste from the guidebook ): 我有几种以以下方式声明的关系(基本上是从guidebook复制粘贴):

class Order extends \yii\db\ActiveRecord {

/* other code */

public function getAffiliate()
{
    return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}

Whenever I try to echo or w/e $order->affiliate->name ; 每当我尝试回显或带有$order->affiliate->name I get the following error: 我收到以下错误:

yii\base\ErrorException: Trying to get property of non-object

I've got no experience with Yii1 what so ever. 我还没有使用Yii1的经验。 Something weird about this project is the database. 关于这个项目的怪异之处是数据库。 All tables start with yii_tablename and id's are: id_tablename . 所有表yii_tablename开头,并且id为: id_tablename Was that normal for Yii1 and could this be causing the issue above? Yii1正常吗,这是否可能导致上述问题?

Edit : When I execute the function like so: $order->getAffilate() it returns an ActiveQuery WITHOUT the data from the affiliate. 编辑 :当我执行这样的功能: $order->getAffilate()它将返回一个ActiveQuery,而没有来自会员的数据。

When I execute the following: 当我执行以下命令时:

$order->getBillingAddress()->one();

I get a weird error: 我收到一个奇怪的错误:

Getting unknown property: app\models\Order::billing
return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);

It's mean that when you call $order->affiliate yii2 will find in Affiliate table on id_affiliate field current Order affiliate_id value and selected one value. 这意味着,当您调用$order->affiliate yii2时,将在id_affiliate字段的“ Affiliate表中找到当前Order affiliate_id值并选择one值。

Check that you have right field names and database have right data. 检查您是否具有正确的字段名称,并且数据库具有正确的数据。

When you call $order->affiliate you will get Affiliate object. 当您调用$order->affiliate您将获得Affiliate对象。 But if you call $order->getAffiliate() you will get ActiveQuery object. 但是,如果调用$order->getAffiliate() ,则将获得ActiveQuery对象。

I found a solution. 我找到了解决方案。 One which I don't really like though, but it does the job. 虽然我不是很喜欢,但是确实可以。 Was reading this thread: link . 正在阅读此线程: link

Kartik V 卡迪克五世

The problem is clearly in uniqueness in naming your relation and your model attribute. 问题显然是在命名关系和模型属性时存在唯一性。 In your User model, you have an attribute named role and you also have a relation getter named getRole. 在用户模型中,您有一个名为role的属性,并且还有一个名为getRole的关系获取器。

So I changed the name of the getter like so: 因此,我像这样更改了吸气剂的名称:

public function getOrderAffiliate()
{
    return $this->hasOne(Affiliate::className(), ['id_affiliate' => 'affiliate_id']);
}

And that fixed the issue. 这就解决了问题。 Never had this issue before and wonder why this happened though. 以前从未遇到过这个问题,想知道为什么会这样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM