【问题标题】:Yii how to search models across relationsYii 如何跨关系搜索模型
【发布时间】:2014-01-20 22:17:25
【问题描述】:

如何在相关模型中搜索模型?我有一个作者模型和一个帖子模型。作者模型与帖子具有“HAS_MANY”关系,而帖子与作者具有“BELONGS_TO”关系。本质上,每个作者都有很多帖子。给定作者姓名和帖子名称,我需要获得满足此条件的帖子。由于作者姓名和帖子名称的组合是唯一的,因此只有一个匹配项。 (这个,我有工作)“作者姓名”与作者模型一起存在,“帖子名称”与帖子模型一起存在。

对于非关系模型,我一直使用它来查找模型:

ExampleModel::model()->findByAttributes(array('name' => $nameInput));

但我似乎无法弄清楚如何像上面描述的那样搜索关系。

【问题讨论】:

    标签: php yii


    【解决方案1】:

    使用CDbCriteria 实例和CActiveRecord::find() 代替,即

    $c=new CDbCriteria
    
    $c->together=true; 
    $c->with=array('author'); //the name of the related model in the model you are searching
    
    // the format for searching related fields is relation.field
    $c->compare('author.name',$nameInput);
    $c->compare('name',$postInput);
    
    $post=Post::model()->find($c);
    

    【讨论】:

    • 简单而简短。你是救生员! =) cmets 也很棒。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多