PHP code example of sowork / phalcon-eagerload

1. Go to this page and download the library: Download sowork/phalcon-eagerload library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

sowork / phalcon-eagerload example snippets


  
  
  namespace Phalcon\Mvc\Model;
  use Sowork\EagerLoad\Traits\EagerLoadingTrait;
  
  /**
   * Class User
   * @package App\Models
   */
  class Book extends Model
  {
      use EagerLoadingTrait;
      public function getSource()
      {
          return 'users';
      }
  
      public function initialize()
      {
          parent::initialize();
          $this->belongsTo( 'id', App\Author::class,'bookId', [
              'alias' => 'blogs'
          ]);
      }
  }
  

  // 加载单个关联关系
  $books = App\Book::with('author')->findFirst([
      'conditions' => 'id = 10',
  ]);
  
  // 加载多个关联关系
  $books = App\Book::with('author', 'publisher')->find();
  
  // 加载嵌套关联关系
  $books = App\Book::with('author.contacts')->find();
  
  // 加载带条件约束的关联关系
  $users = App\User::with(['posts' => function ($query) {
      $query->where('id = 10');
  }])->find();
  

    // 这在你需要动态决定是否加载关联模型时可能很有用
    $books = App\Book::find(); // or App\Book::findFirst()
    
    if ($someCondition) {
        $books->load('author', 'publisher');
    }
    
    // 也可以通过条件限制
  
    $books->load(['author' => function ($query) {
        $query->orderBy('published_date desc');
    }]);