zier
zier

Reputation: 101

HasOne and HasMany for the same Table cakephp

i'd like to set hasOne and hasMany to same model,in a part of my code i need only 1 result, but in other part i need all result (Objects from type Client that will return for a table in my site):

    $this->hasOne('Vendas')
    ->setForeignKey('id_cliente')
    ->setBindingKey('id')
    ;

    $this->hasMany('Vendas')
    ->setForeignKey('id_cliente')
    ->setBidingKey('id');

This is possible, or i made a mistake?

Upvotes: 0

Views: 792

Answers (2)

floriank
floriank

Reputation: 25698

Read the manual https://book.cakephp.org/3.0/en/orm/associations.html. Read the whole page carefully.

  • className: the class name of the table being associated to the current model. If you’re defining a ‘User hasOne Address’ relationship, the className key should equal ‘Addresses’.
  • conditions: an array of find() compatible conditions such as ['Addresses.primary' => true]

Define the class name and conditions you need for your assocs.

    $this->hasOne('Foo', [
        'className' => 'Foo',
        'conditions' => [/* whatever you need*/]
    ]);

    $this->hasMany('Bar', [
        'className' => 'Foo',
        'conditions' => [/* whatever you need*/]
    ]);

Upvotes: 1

SrThompson
SrThompson

Reputation: 5748

If the relationship is 1-* you should define the relationship as hasMany(). Then you write a query for one result and a query for multiple results

Upvotes: 0

Related Questions