LARAVEL Selecting 2 tables at the same time

Paco Pinazo Guna :

I have an animals table and images table.

Images has Id_animal.

The problem is that in AnimalController I am selecting the last 6 animals and I want to return their images at the same time.

I don't have any idea how to do it.

public static function getNewerAnimals()
{
    $animales = DB::table('animals')
    ->orderBy('date_found')
    ->limit(6)
    ->get();

    return $animales;
}

Animals Table

Images Table

Dilip Hirapara :

You can use join for join two tables.

 $animales = DB::table('animals')
    ->orderBy('date_found')
    ->join('images','images.id_animal','animals.id')
    ->limit(6)
    ->get();
return view('viewname',compact('animales'))

Edit

In blade file

@foreach($animales as $animal)
    {{ $animal->nickname  }}
@endforeach

And if you want to use by relationship then it'll have hasMany relationship.

Animal model

class Animal extends Model
{
    protected $table = 'animals';
    public function images()
    {
        return $this->hasMany('App\Image','id_animal','id')->where('type','interest');
    }
}

And in controller

$animales = Animal::with('images')
    ->orderBy('date_found')
    ->limit(6)
    ->get();

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=372546&siteId=1