【问题标题】:Condition for related table ORM Kohana相关表 ORM Kohana 的条件
【发布时间】:2014-06-19 12:22:28
【问题描述】:

例如我有 3 个表:

songs(id, song_name)
song_category(id, song_id, category_id)
categories(id, name)

我想获取 id 高于 5 的类别的歌曲。我想使用 ORM 来完成,而不是使用简单的 SQL 查询。是否可以使用这样的一个查询来做到这一点:

$songs = ORM::factory("songs")->where("category.id > 5")

【问题讨论】:

    标签: php orm kohana


    【解决方案1】:

    不,你不能通过一个 Kohana ORM 调用来做到这一点。

    我发现最好的方法是这样的,它对 ORM 将生成的 SQL 查询进行修改:

    // Get the basic "song" model
    $songs = ORM::factory("songs");
    
    // Get the information about how it is connected to
    // the "category" model using the `through` model
    $song_relations = $results->has_many();
    $category_relation = $song_relations['categories'];
    $through = $category_relation['through'];
    
    // Join on `through` model's target foreign key (far_key) and `target` model's primary key
    $join_col1 = $through.'.'.$category_relation['foreign_key'];
    $join_col2 = $songs->object_name().'.'.$songs->primary_key();
    $songs->join($through)->on($join_col1, '=', $join_col2);
    
    // Now, filter on the 
    $songs->where($through.'.'.$category_relation['far_key'], '>', 5);
    
    $arr = $results->find_all()->as_array();
    

    您可以通过硬编码 join 方法调用中的值来节省一些代码,但这种方式利用了您已有的 ORM 关系定义。

    这假定您的 Song 模型中包含以下代码:

    protected $_has_many = [
        'categories' => [
            'model'       => 'category',
            'through'     => 'song_category',
            'foreign_key' => 'song_id',
            'far_key'     => 'category_id',
        ]
    ];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-11
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 2011-03-24
      相关资源
      最近更新 更多