我遇到以下错误:
未找到列:1054未知列'image_likes.gallery_image_id' 在“ where子句”中(SQL:从
image_likes
中选择* where {1)中的image_likes
。gallery_image_id
和deleted_at
为空,user_id
= 1和image_likes
。deleted_at
为空)
每当我添加function ($query)
时。
下面的代码行获取数据,但是我需要数据来获取与之对应的赞。
$images = GalleryImage::with('user')->get()
这是我到目前为止所拥有的。
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;
}
}
答案 0 :(得分:2)
在模型GalleryImage中为likes
更改您的关系
public function likes()
{
return $this->hasMany(ImageLike::class, 'image_id'); //here image_id is reference id of images table to likes table
}
默认laravel假设您的模型名称和_id为外键,因此它在gallery_image_id
模型中为GalleryImage模型寻找ImageLike
,但是您有image_id
。因此,如果您没有默认值,请在关系中进行具体说明。
return $this->hasMany('App\Comment', 'foreign_key', 'local_key');
在此处查看详细信息
https://laravel.com/docs/5.6/eloquent-relationships#one-to-many
答案 1 :(得分:1)
public function likedByMe()
{
return $this->likes()->whereUserId(auth()->id)->count()>0;
}
这与您的问题无关,但是您可以像这样高效地重写likedByMe()