i'm getting the following error:
Column not found: 1054 Unknown column 'image_likes.gallery_image_id' in 'where clause' (SQL: select * from
image_likes
whereimage_likes
.gallery_image_id
in (1) anddeleted_at
is null anduser_id
= 1 andimage_likes
.deleted_at
is null)
whenever i add the function ($query)
.
the line of code below gets the data, but i need the data to get the likes that corresponds with it.
$images = GalleryImage::with('user')->get()
this is what i have so far.
ImageLike.php
<?php
namespace App;
use App\GalleryImage;
use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ImageLike extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id',
'image_id'
];
}
ImageController.php
public function getImages()
{
$images = GalleryImage::with('user')
->with(['likes' => function ($query) {
$query->whereNull('deleted_at');
$query->where('user_id', auth()->user()->id);
}])->get();
return response()->json($images);
}
GalleryImage.php
<?php
namespace App;
use App\User;
use App\GalleryImage;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\User as Authenticatable;
class GalleryImage extends Authenticatable
{
protected $fillable = [
'image_title',
'user_id',
'file_name',
'created_at'
];
protected $table = 'images';
public function user()
{
return $this->belongsTo(User::class);
}
public function likes()
{
return $this->hasMany(ImageLike::class);
}
public function likedByMe()
{
foreach($this->likes as $like) {
if ($like->user_id == auth()->id()){
return true;
}
}
return false;
}
}
Change your relationship in model GalleryImage for likes
public function likes()
{
return $this->hasMany(ImageLike::class, 'image_id'); //here image_id is reference id of images table to likes table
}
default laravel assume your model name and _id as foreign key so it was looking for gallery_image_id
for your GalleryImage model in ImageLike
model but you have image_id
. So if you have other than default then specific it in relationship.
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
check details here
https://laravel.com/docs/5.6/eloquent-relationships#one-to-many
public function likedByMe()
{
return $this->likes()->whereUserId(auth()->id)->count()>0;
}
this is not regarding you problem but, you can re-write your likedByMe()
like this in more efficient way