fuel / orm

Fuel PHP Framework - Fuel v1.x ORM
http://fuelphp.com/docs/packages/orm/intro.html
151 stars 95 forks source link

Add distinct parameter to \Orm\Query #386

Closed jidaikobo-shibata closed 9 years ago

jidaikobo-shibata commented 9 years ago

I want to add to distinct parameter to \Orm\Query. I think this modification is harmless and useful. Please consider below.

add member variable.

/**
 * @var  bool  is distinct
 */
protected $distinct;

add to __construct().

case 'distinct':
    $this->distinct($val);
    break;

add function.

/**
 * Set distinct
 *
 * @param   bool $bool
 *
 * @return  $this
 */
public function distinct($bool)
{
    $this->distinct = intval($bool);

    return $this;
}

add to build_query().

    // distinct
    ! is_null($this->distinct) and $query->distinct($this->distinct);

then I can use

$options['distinct'] = true;
\Model_Something('all', $options);

thanks and forgive me about bad english.

WanWizard commented 9 years ago

That doesn't really do anything.

The DISTINCT keyword in SQL filters unique rows, but in an ORM query, all rows are unique since ORM tables require a primary key, and primary keys are per definition unique. So this might only work in combination with select(), which is not really supported.

Also, if you would include relations in your query, you might also end up with an incomplete ORM result cache due to the filtered results.

jidaikobo-shibata commented 9 years ago

Thank you for giving me a quick answer and hint. My relation tables doesn't have multiple primary keys.

\DBUtil::create_table('cases_keywords', array(
    'case_id' => array('constraint' => 11, 'type' => 'int'),
    'keyword_id' => array('constraint' => 11, 'type' => 'int'),
));

I should write below

\DBUtil::create_table('cases_keywords', array(
    'case_id' => array('constraint' => 11, 'type' => 'int'),
    'keyword_id' => array('constraint' => 11, 'type' => 'int'),
    PRIMARY KEY (`case_id`,`keyword_id`)
));

this modification gives me a better result. but it seems some issues remains for me around \Orm\Query::get() when I'm using many_many. I want to pursue this. so, please wait to close this issue.

jidaikobo-shibata commented 9 years ago

WanWizard, Thank you for giving me a chance to dive into ORM and I want to apologize to have took your time to answer me by my shallow code reading. I understood what you explained.

many_many relations gives me a many patterns of results because \Fuel\Core\Database_Query_Builder_Select::compile() generates select phrase within relations' fields. So, distinct never work what I wanted.

what I had to do was just use "group_by".

Thanks again.