XF 2.0 Does fetchOne() auto-include limit(1) and can I query the other table without a one-to-many relationship?

Marcus

Well-known member
I have two questions here:

1. If there exist multiple result items, can I use just fetchOne() and does it always include limit(1)?

2. Can I write the query as below, or would it need a one-to-many relationship and should be written as where(Sugar|brown)?

PHP:
/** @var \XF\Mvc\Entity\Finder $mojito*/
$mojitos= \XF::app()->finder('XF:Lemon')
    ->with('Sugar',true)
    ->where([
        'Sugar.type' => "brown",
        'cold' => 'yes',
        'rum' => 'yes'
    ])
    ->fetchOne();
 
Last edited:
Or should I use this:

PHP:
/** @var \XF\Mvc\Entity\Finder $mojitos*/
$mojitos= \XF::app()->finder('XF:Lemon')
    ->with('Sugar',true)
    ->where([
        'cold' => 'yes',
        'rum' => 'yes'
    ])
    ->order('RAND()') // do I have to write this?
    ->limit(1) // do I have to write this?
    ->fetchOne();

$drink = $mojitos->Sugar->brown->fetchOne();
 
For the second question, the table Sugar and Lemon have a One-to-One relationship described in the entity. Can I write it ->where(['Sugar.type' => "brown", ... ? I want to extend the current model, I guess I can not have this at the same time, all in one entity relationship description?
  • Lemon - One-to-One - Sugar
  • Lemon - One-to-Many - Sugar
 
For the second question, the table Sugar and Lemon have a One-to-One relationship described in the entity. Can I write it ->where(['Sugar.type' => "brown", ... ? I want to extend the current model, I guess I can not have this at the same time, all in one entity relationship description?
  • Lemon - One-to-One - Sugar
  • Lemon - One-to-Many - Sugar

You can have that, you’d define it as 2 relations and then in th conditions array for one you’d define the value of the sugar.type field.

I’m on my phone at the moment, so I can’t show you in more detail, sorry...

Liam
 
I think multiple relationships between the same entities are possible by just using a different alias:

  • Lemon - One-to-One - Sugar. ALIAS-NAME: Sugar (as it was set before)
  • Lemon - One-to-Many - Sugar. ALIAS-NAME: SugarType
PHP:
/** @var \XF\Mvc\Entity\Finder $mojito*/
// added relationship in Lemon (!) entity: Lemon - One-to-Many - Sugar. ALIAS-NAME: SugarType

$mojitos= \XF::app()->finder('XF:Lemon')
    ->with('Sugar',true)
    ->with('SugarType|brown')  // one-to-many
    ->where([
        'cold' => 'yes',
        'rum' => 'yes'
    ])
    ->fetchOne();
 
You could also do something like this in your structure:

PHP:
$structure->relations = [
    'SugarBrown' => [
        'entity' => '',
        'type' => self::TO_ONE,
        'conditions' => [
            ['$type', '=', 'brown']
            'sugar_id'
        ]
    ]
    // Other to many sugar relation
]

I think thats what you're going for?

Liam
 
Back
Top Bottom