CakePHP アソシエーション機能

モデル

※src\Model\Table\ProductsTable.php
class ProductsTable extends Table
{
  public function initialize(array $config)
  {
    ~
    $this->hasOne('Receipt', [
      'foreignKey' => 'product_id',
      'bindingKey' => 'id'
    ]);
    
    $this->hasMany(~, [
      'foreignKey' => ~,
    ]);
  }
}

※src\Model\Table\ReceiptTable.php
class ReceiptTable extends Table
{
  public function initialize(array $config)
  {
    ~
    $this->belongsTo('Users', [
      'foreignKey' => 'user_id',
      'joinType' => 'INNER',
    ]);

    $this->belongsTo('Products', [
      'foreignKey' => 'product_id',
      'joinType' => 'RIGHT',
    ]);
  }
}

コントローラ

※src\Controller\WatchesController.php
class WatchesController extends AppController
{
  public function productList(){

   $products = $this->Products
    ->find()
    ->contain(['receipt'])
    ->where(['Products.col1!=' => '0'])
    ;

    $this->set(compact('products'));
  }
}

※src\Controller\AdminsController.php
class AdminsController extends AppController
{
  public function receipt(){
    $receipts = $this->paginate(
      $this->Receipt
       ->find()
       ->contain(['products', 'users'])
       );

    $this->log($receipts);

    $this->set(compact('receipts'));
  }
}

ビュー

※src\Template\Watches\product_list.ctp
<table>
  ~
  <?php foreach ($products as $product): ?>
  <tr>
   <td><?= h($product->col1) ?></td>
    <td><?= h($product->Receipt['col1']) ?></td>
  </tr>
  <?php endforeach; ?>
</table>

コメントを残す

メールアドレスが公開されることはありません。