How To Use ‘Contain’ Method In CakePHP 3.0 Query Builder

How To Use ‘Contain’ Method In CakePHP 3.0 Query Builder
Social sharing

A basic query in CakePHP 3.0 is different than the ones used in CakePHP 2.0. In 3.0, the ORM (Object-relational mapping) used for database management related operations has completely changed.  For example, if ‘Articles‘ is a model & we have to fetch some of the fields using query builder, the query would look as below:

$results=$articles->find()
->where(['id >'=>1])
->order(['title'=>'DESC'])
->toArray();

Here we get all the records from ‘Articles’ table where id is greater than 1 & the results are sorted in descending order by the field ‘title’.

Let’s take this example. There are 2 tables such as ‘Tag’ & ‘Article’ with many to one relationship. In case we need to fetch the tag information associated with articles, then we opt for the ‘contain’ method of CakePHP. In version 3.0 we have full control over the associated models. Here is the query:

$results=$articles->find()
->contain(['Authors', Tags])
->where(['id >'=>1])
->order(['title'=>'DESC'])
->toArray();

By default, the ‘Contain’ method selects all the fields from associated tables. If we wish to select only a few & leave the rest, we have to query like the following:

$results=$articles->find()
->contain(['Authors'=> function ($q) {									
return $q->select(['id', article_id, author_name])->autoFields(false);
	}, Tags])
		->where(['id >'=>1])
		->order(['title'=>'DESC'])
		->toArray();

In order to select an individual field, we have to set the autoFields to false. To filter associated records based on conditions, here’s how it is:

$results=$articles->find()
->contain(['Authors'=> function ($q) {								
return $q->select(['id', article_id, author_name])
->where(['Authors.article_id' =>1])
->autoFields(false);
	}, Tags])
		->where(['id >'=>1])
		->order(['title'=>'DESC'])
		->toArray();

We can also attach formatter functions to the associated table to get specific results. Suppose, we have a birth date column in the author table & we want to get the author’s current age; we can attach a formatter function to the query.

For example,

$query->contain(['Authors'=>function ($q) {
return$q->formatResults(function ($authors) {
return$authors->map(function ($author) {
$author['age'] =$author['birth_date']->diff(new\DateTime)->y;
return$author;
        });
    });
});
$results=$query->all();
echo$results->first()->author->age;  //Give the age of the author

Get all your queries answered from Andolasoft‘s experienced pool of CakePHP Developers. Planning anything on CakePHP? We would love to get in touch wi/th you.

Check out our flagship product – Orangescrum built completely with CakePHP. Also, share your comments below.

Your recently viewed posts:

Jayadev Das - Post Author

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘About Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box