1

I am trying to make the relationship between the tables, but can’t figure out what I doing wrong.

I read The documentations in cakephp3, and tons of post in stackoverflow, and still can’t get any result.

         --------------------------
name    |invoices     |shares      |
var     |id           |id          |
var     |             |idBill      |
         --------------------------

The relationship should be from idBill in shares and id in invoices

class SharesTable extends Table {
    public function initialize(array $config) {
        parent::initialize($config);

        $this->belongsTo('invoices', [
        'className' => 'App\Model\Table\InvoicesTable',
        'foreignKey' => 'idBill',
        'targetForeignKey' => 'id'
        ]);
    }
}

And in controller try to print the bill associate to the share like this:

public function view($id = null)
{
    $share = $this->Shares->get($id, [
      'contain' => []
    ]);
    var_dump( $share->invoices );

    $this->set('share', $share);
}

I just expect to print the bill but I always get null

ndm
  • 59,784
  • 9
  • 71
  • 110
Angel
  • 55
  • 1
  • 10

1 Answers1

1

Your contain is empty, so you won't receive any associations. Also the default entity property name for belongsTo (and hasOne) associations is the singular, underscored variant of the association name, ie invoice, not invoices.

It's also recommended to use association names that do match the table alias, that is Invoices (with a capital I) for InvoicesTable, that way it will find the class automatically and you don't have to specify it via the className option (also there is no targetForeignKey option for belongsTo associations).

$this->belongsTo('Invoices', [
    'foreignKey' => 'idBill'
]);
$share = $this->Shares->get($id, [
  'contain' => ['Invoices']
]);

debug($share->invoice);

See also

ndm
  • 59,784
  • 9
  • 71
  • 110