我的目标是有可能通过用户名和姓氏搜索文档,也可以通过重建年份和学期。
文档只与声明相关,因此文档与一个声明相关,而声明可以与一个或没有文档相关。
声明与外出学生和重新创作有关。
所以在查询文档时,我想通过声明表查询学生和重新计算。
我的文档关系代码:

return array(
                        'declaration' => array(self::BELONGS_TO, 'Declaration', 'DeclarationID'),
            'outgoingStudentUserIdUser' => array(self::HAS_ONE, 'OutgoingStudent', 'OutgoingStudent_User_idUser','through'=>'declaration',),
                'Recrutation' => array(self::HAS_ONE, 'Recrutation', 'Recrutation_RecrutationID','through'=>'declaration'),
                );

现在在search()函数中,我想用
'declaration','outgoingStudentUserIdUser' and 'Recrutation':

                $criteria->with = array('declaration','Recrutation','outgoingStudentUserIdUser');

我得到这个错误:
CDbCommand nie zdołałwykonaćinstrukcji SQL:SQLSTATE[42000][1066]
不是唯一的表/别名:“declaration”。执行的SQL语句是:
tDeclarationID左侧选择COUNT(DISTINCTDocumentst
外部连接打开
Declarationsdeclaration=tDeclarationID)左外连接
declarationidDeclarations打开
RecrutationRecrutation=declarationRecrutation_RecrutationID
左外部连接打开
RecrutationRecrutationID=Declarationsdeclaration)左外连接
tDeclarationID打开
declarationidDeclarations=OutgoingStudentoutgoingStudentUserIdUser
当只使用declarationOutgoingStudent_User_idUser时,只有同时使用两者时才没有错误。
所以也许应该换个方式来做,但是怎么做呢?

最佳答案

我有很多事情要告诉你!它们在这里:
我发现您的关系函数声明非常混乱,我不确定它是否在做您希望它做的事情(以防它起作用)。以下是我的建议:
首先,“outgoingStudentUserIdUser”对于一个关系来说是个糟糕的名字。最后,关系将是outgoingStudentUser的实例,而不仅仅是“id”。所以请允许我将其命名为outgoingStudentUser。现在,这是我的代码:

  'outgoingStudentUser' => array(self::HAS_ONE, 'OutgoingStudent', array('idDocuments'=>'idOutgoingStudent'),'through'=>'declaration',),

其中“idDocuments”是文档的模型主键,而idOutgoingStudent是OutgoingStudent的模型主键。
第二种关系可以用非常相似的方式加以修正:
 'Recrutation' => array(self::HAS_ONE, 'Recrutation', array('idDocuments'=>'idRecrutation'),'through'=>'declaration'),

其中“idDocuments”是文档的模型主键,idRecrutation是重新计算的模型主键。
您可以在这里找到正确的声明:http://www.yiiframework.com/doc/guide/1.1/en/database.arr#through-on-self
但还不止这些。我还有更多要告诉你的!你用你的代码做的是毫无意义的with'用于强制相关对象进行紧急加载。在以下代码中:
$criteria->with = array('declaration','Recrutation','outgoingStudentUserIdUser');

您只需在$criteria中指定,当您在DB中检索使用此$criteria的文档实例时,它还将通过作为参数传递给“with”的关系来获取链接到该实例的模型。那是迫不及待的装载。它用于减少对数据库的查询数量。就像说:“去数据库给我这个文档实例,但是一旦你到了那里,给我每个与这个对象相关的其他表的实例一次”。
好吧,这是你要声明的,但肯定不是你想做的。我怎么知道?因为这个声明在search()函数中是无用的。如您所见:http://www.yiiframework.com/doc/api/1.1/CDbCriteria/#with-detail,“with”仅在某些函数中有用,search()不是其中之一。在search()中,急切的加载是毫无意义、毫无意义和无用的。
所以我觉得我不得不问你你想做什么?你说:“我的目标是有可能通过用户名和姓氏搜索文档,也可以通过重现年份和学期搜索文档”,但你所说的“通过用户名和…”搜索文档是什么意思?是否希望像这样:$user->documents返回与$user关联的所有文档?我希望你能更具体些,但也许在另一个更切题的问题上。

关于php - Yii Framework-通过同一“通过”表的两个关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8688273/

10-11 05:04
查看更多