Ç°ÑÔ
hasOne¡¢hasManyÊÇYii2ÌØÓеÄÓÃÓÚ¶a±i¹ØÁª²eѯµÄº¯Êý£¬Æ½Ê±ÔÚʹÓöa±i¹ØÁª²eѯµÄʱºo½¨ÒeʹÓÃËuÃÇ¡£ÎªÊ²Ã´£¿ÒoΪÕaÖֽʽ¹ØÁª²eѯ³oÀ´µÄ½a¹u»a±£ÁoYii2×ÔÓеıiÍÅÅÐo¹¦ÄÜ£¬ÒÔ¼°CheckboxColumnÖÐinputµÄid´aeÖµ£¬ÖÁÓÚ»¹ÓÐûÓÐÆaËuµÄºÃ´¦¾ÍÐeÒª´o¼ÒÈ¥ÍÚ¾oÁË£¬±ÊÕßÄ¿Ç°¾Í¢ÏÖÁËÕaÁ½¸o³£Óõĺô¦¡£ÆaËuµÄ¹ØÁª²eѯ£¬ÏñyiidbQuery²eѯ»oÕßÔÉuµÄSQLÓi¾a²eѯ¶¼Ã»ÓУ¬²eѯ³oÀ´ÔÚÁбiչʾµÄʱºo£¬±iÍÒ»Åźڡ£
Yii2µÄhasOne¡¢hasMany¶a±i¹ØÁª²eѯ£¬²»¹ÜÊÇÎĵµ»¹ÊÇÎÄÕÂÆaʵ¶¼¿ÉÒÔÇa¶øÒ×¾ÙµÄÕÒµ½²Î¿¼Ä¸±¾£¬µ«ÊDZÊÕßΪʲô»¹ÒªÐ´ÕaƪÎÄÕÂÄØ£¬Ïe¨ÆaʵҲºÜ¼oµ¥£¬ÒoΪÔÚÇ°ÃaeµÄÐÅÏ¢ÖÐÎÒûÓп´µ½¶a¶Ô¶a¹ØÁª²eѯµÄÓ裬²»Öظ´±ðÈË£¬Ò²Öظ´×Ô¼º£¬±¾ÎĵÄÖصa¾Í½²¶a¶Ô¶a¹ØÁª²eѯµÄÓÃ*¨£¬ÈÃÄaÕÇÕÇ֪ʶ¡£
*ÐeÇoÖÎo**
1¡¢Ê¹ÓÃÒ»Ìo²eѯÓi¾a¾ÍÄÜ°ÑÁбiµÄÊý¾ÝÈ«²¿Õ¹ÏÖ³oÀ´£¬Áбi°uº¬Ò»¶ÔÒ»£¬Ò»¶Ô¶a£¬ÒÔ¼°¶a¶Ô¶aµÄ¹Øϵ¡£
2¡¢²»ÄÜÆÆ»µYii2×ÔÓеıiÍ*ÅÅÐo¹¦ÄÜ£¬ÒÔ¼°CheckboxColumnÖÐinputµÄid´aeÖµ¡£
Ч¹uͼ
1¡¢Ò»¶ÔÒ»£¬Ò»¶Ô¶a£¬¶a¶Ô¶a£¬±iÍ*ÅÅÐo¡£
2¡¢CheckboxColumnÖÐinputµÄidÖµ¡£
*´uÂeÖÎo**
¶a¶Ô¶a
Àý×Ó£ºÒ»¸o¿Í»§¿ÉÒÔÓжa¸o±eÇ(C)£¬Ò»¸o±eÇ(C)¿ÉÒÔ¶Ô¶a¸o¿Í»§¡£
1¡¢ÔÚTSales£¨¿Í»§±iµÄ model£(C)Ài¼ÓÈeÈçÏ´uÂe£º
public function getcommon_tag()
{
return $this->hasMany(CommonTag::className(), ['itemid' => 't_id'])->onCondition(['idtype' => "ÄÚÈÝ"])->joinWith(['tag']);
}
×¢ÊÍ£ºÕaÀicommon_tag±iΪÖмa±i£¬common_tagÖмa±iÓÃhasManyÓe¿Í»§±i¹ØÁªÖ®ºoÒªÔÚºoÃae¼ÓÉÏjoinWith(['tag'])¹ØÁª±eÇ(C)±i¡£onConditionΪ¸½¼ÓÌo¼þµÄ½¨¡£
2¡¢ÔÚCommonTag£¨Öмa±i model£(C)Ài¼ÓÈeÈçÏ´uÂe¹ØÁª±eÇ(C)±i£¬ÓÃhasOne¾ÍÐС£
public function gettag()
{
return $this->hasOne(Tag::className(), ['id'=>'tagid']);
}
3¡¢ÔÚTSalesSearch£¨¿Í»§µÄSearch model£(C) Ài¼ÓÈeÈçÏ´uÂe¹ØÁªcommon_tagÖмa±i£º $query->joinWith(['common_tag']);
4¡¢Ò³ÃaeÊa³o´uÂeÈçÏÂ:
[
'attribute' => 'tag_id',
'value' => function ($model) {
$_tag=$model->getRelatedRecords()['common_tag'];
if(!empty($_tag)){
$tagName="";
foreach ($_tag as $key => $value) { $tagName.=$value['tag']['name'].'/';
}
return rtrim($tagName,'/');
}
},
],
×¢ÊÍ£º$model->getRelatedRecords() ÊÇÓÃÓÚ»ñÈ¡[_related:yiidbBaseActiveRecord:private]Êý×eµÄÖµ¡£
Ò»¶Ô¶a
1¡¢ÔÚÇ°ÃaeµÄ¶a¶Ô¶aÓèÖÐÉae¼°µ½µÄhasMany¾ÍÊoÓÚÒ»¶Ô¶aµÄÓ裬ҪʵÏÖÒ»¶Ô¶aµÄ»°¾Í°ÑºoÃaeµÄjoinWithÈ¥µo¾Í¿ÉÒÔÁË£¬ÆaËuÅaÖÃÒÔ¼°Êa³o*½Ê½¶¼Ò»Ñu¡£
Ò»¶ÔÒ»
1¡¢Ò»¶ÔÒ»µÄÓèǰÃaeÒ²Éae¼°ÁË£¬hasOne¾ÍÊoÓÚÒ»¶ÔÒ»µÄÓ裬ÅaÖúÍhasManyÒ»Ñu£¬ÕaÀi¾Í²»ÏeÊoÁË¡£
×¢ÒaÊÂÏi
1¡¢µ±¹ØÁª²eѯ³oÀ´µÄֵʹÓÃÈçÏ´uÂeÊa³o£¨common_tag.name£(C)»ñÈ¡²»µ½ÖµµÄʱºo£¬ÄǾÍÓ¦¸ÃÊÇÄaµÄ¿Í»§±i´aeÔÚÕa¸oname×ֶΣ¬²¢ÇÒÕa¸oֵΪ¿Õ£¬ÖØÃuÁËÖ®ºo¾Í»aÓÅÏÈÊa³oÖ÷±iµÄ×ֶΣ¬½a¾o°i*¨Óãº$model->getRelatedRecords()»ñÈ¡¡£
[
'attribute' => 'tag_id',
'value' => 'common_tag.name'
]
ÒÔÉÏËuÊoÊÇС±a¸ø´o¼Ò½eÉܵÄYii2ÖÐhasOne¡¢hasMany¼°¶a¶Ô¶a¹ØÁª²eѯµÄÓèÏe½a£¬Ï£Íu¶Ô´o¼ÒÓÐËu°iÖu£¬Èç¹u´o¼ÒÓÐÈκÎÒÉÎÊÇe¸øÎÒÁoÑÔ£¬Ð¡±a»a¼°Ê±»Ø¸´´o¼ÒµÄ¡£ÔÚ´ËҲdz£¸Ðл´o¼Ò¶Ô½Å±¾Ö®¼ÒÍøÕ¾µÄÖ§³Ö£¡