QueryBuilder limit is working for only first row in cakephp 3.2 [duplicate]

倖福魔咒の 提交于 2019-12-04 06:29:06

问题


Hii i am new to cakephp 3.2 v. Here i have used model association (hasMany). Here in bind section (campaign_videos) ,i want to fetch only one record , so for this ,i have put below code to manage it. my actual data in db.

[
    {
        "id": 1,
        "user_id": 95,

        "campaign_videos": [
            {
                "id": 1,
                "campaign_id": 1,

            },
            {
                "id": 3,
                "campaign_id": 1,

            }
        ]
    },
    {
        "id": 2,
        "user_id": 95,

        "campaign_videos": [
            {
                "id": 2,
                "campaign_id": 2,

            }
        ]
    },
  $fetchCampaignFirst = $this->Campaigns->find()->contain(['CampaignVideos' => ['queryBuilder' => function ($q) {
                            return $q->limit(1);
                        }]]);

I am getting this limit working for first data only ,not for others (others even not showing the fetched data).

Below i have written the output

Here i want to get an output like

[
    {
        "id": 1,
        "user_id": 95,
         "campaign_videos": [
            {
                "id": 1,
                "campaign_id": 1,

            },
         ]
    },
    {
        "id": 2,
        "user_id": 95,

        "campaign_videos": [
            {
                "id": 2,
                "campaign_id": 2,

            }
        ]
    }]

Only want the first record of campaign_videos. Here after using the queryBuilder query , i am getting out put like.

[
    {
        "id": 1,
        "user_id": 95,
         "campaign_videos": [
            {
                "id": 1,
                "campaign_id": 1,

            },

        ]
    },
    {
        "id": 2,
        "user_id": 95,

        "campaign_videos": [

        ]
    }]

I am not getting any data for second id ,while data is present for it. Please suggest me. Thank you in advance.


回答1:


Maybe I'm wrong (so feel free to downvote my answer) but I think it's not feasible using a simple query

in fact cake, when loading associated data, does a single query on the associated table and after that matches the rows with the corresponding ones in the main table.

So you would need to do a mysql query that find the first record of every category. i.e. something like what is described in this article

I think that the only (or maybe the simpler) solution is to loop through your records:

$campaigns= $this->Campaigns->find();

foreach($campaigns as $campaign)
{
    $campaign->campaign_videos = $this->Campaigns->CampaignVideos-find()
        ->where(['campaign_id' => $campaign->id]
        ->order(['id' => 'asc'])
        ->limit(1);
}


来源:https://stackoverflow.com/questions/37292207/querybuilder-limit-is-working-for-only-first-row-in-cakephp-3-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!