ampedo
ampedo

Reputation: 253

Laravel query two table

Hello just a question from a newbie i just to query this two and i want the second table to be inside the array of the other table.

the table looks like this

bulletin

|d : 1"|
|content: "test"|
|id : 2|
|content: "test2"|

images

|id : 1|
|bulletin_id: 1|
|upload_name: 1.jpg|
|id : 2|
|bulletin_id: 1|
|upload_name: 2.jpg|
|id : 3|
|bulletin_id: 2|
|upload_name: 3.jpg|
|id : 4|
|bulletin_id: 2|
|upload_name: 2.jpg|

my query looks like this

$bulletin = DB::table('bulletin')
            ->select('bulletin.id','content','upload_name')
            ->join('images', 'images.bulletin_id', '=', 'bulletin.id')
            ->get();

is it possible to get this data look like this

array
(
  id:1,
  content:test,
  upload_name:array
(
   1.jpg,
   2.jpg
)
)

Upvotes: 0

Views: 260

Answers (1)

Kenny Horna
Kenny Horna

Reputation: 14251

First define your models.

php artisan make:model Bulletin
php artisan make:model Image

App\Bulletin.php

protected $table = 'bulletin';

Then the relationship:

App\Bulletin.php

use Image;

//

public function upload_name()
{
    return $this->hasMany(Image::class);
}

So now you can query your objects:

app\Http\Controllers\BulletinController.php

public function index()
{
    $bulletins = Bulletin::with('upload_name')->get();

    return $bulletins;
}

Upvotes: 1

Related Questions