简体   繁体   中英

Cakephp - get database data from not associated models

I wanted to ask, how can i get data from one table and use this in other find.

For example, i have films table. I want to get highest rated 3 films. Result should return 3 ID's.

Now, i want to create other query from not associated table, and pass this 3 ID's as "conditions" to find data in other table.

I dont want to use associations, because, data is stored in many databases, and this is problematic.

Thank You.

Once you've got your film IDs you can use in to filter the results from your other Model :-

$filmIds = ['32','55','75'];

$query = TableRegistry::get('Model')->find()
    ->where(function ($exp, $q) use ($filmIds) {
        return $exp->in('film_id', $filmIds);
    });
// WHERE film_id IN ('32','55','75')

Check out the docs section on advanced conditions .

If you need to get your film IDs into the correct format ( ie that shown in the example code) you can use Hash::extract() on the results from your previous query.

if your cakephp version 3.x you can use subqueries in fairly intuitive way

$films = TableRegistry::get('Films')->find('highestRated')
->select(['id'])
->limlt(3);

$query = $related->find()
->where(['id' => $films]);

Subqueries are accepted anywhere a query expression can be used. For example, in the select() and join() methods. http://book.cakephp.org/3.0/en/orm/query-builder.html#subqueries

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM