mercredi 28 septembre 2016

laravel join selects all rows instead of specific ones

I have 3 tables.

authors(id, name) 

audio_cat(id, cat_id(foreign key to categories), file_id (fr.key to files), author_id(fr.key to authors table), audio_type)

files(id, type, path)

i want to fetch authors and files(which belongs to specific author). for example, one author may has 3 files, another one has 1, so on.. when i try to fetch specific author's files, it returns all files, instead of files which belongs to this author. here's code in my controller

$authors = [];
    $i = 0;
    foreach($items->all() as $author)
    {
        $authors[$i] = $author;
        $authors[$i]['files'] = $author
            ->join('audio_cat', 'authors.id', '=', 'audio_cat.author_id')
            ->join('files', 'audio_cat.file_id', '=', 'files.id')
            ->select('audio_cat.cat_id', 'audio_cat.author_id', 'audio_cat.file_id','files.id', 'files.name')
            ->get();
        $i++;
    }

    dd($authors);

dump shows this,I have 2 authors, and they have both have 2 audio files

array:2 [▼
  0 => Author {#465 ▶}
  1 => Author {#466 ▶}
]

for example first author

0 => Author {#465 ▼
#fillable: array:4 [▼
  0 => "name"
  1 => "lang"
  2 => "lang_id"
  3 => "user_id"
]

#attributes: array:8 [▼
  "id" => 26
  "user_id" => 2
  "name" => "bar"
  "lang_id" => 26
  "lang" => "en"
  "created_at" => "2016-09-27 09:12:03"
  "updated_at" => "2016-09-27 09:12:08"
  "files" => Collection {#471 ▼
    #items: array:4 [▶]
  }
]

}

files key has 4 arrays in it, it return all 4 files, not that 2 files which belong to this specific author

"files" => Collection {#471 ▼
    #items: array:4 [▼
      0 => Author {#472 ▼
        #fillable: array:4 [▶]
        #table: "authors"
        #connection: null
        #primaryKey: "id"
        #keyType: "int"
        #perPage: 15
        +incrementing: true
        +timestamps: true
        #attributes: array:5 [▶]
        #original: array:5 [▶]
      }
      1 => Author {#473 ▶}
      2 => Author {#474 ▶}
      3 => Author {#475 ▶}
    ]



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2dqYV4y
via IFTTT

Aucun commentaire:

Enregistrer un commentaire