【发布时间】:2018-11-02 18:26:51
【问题描述】:
我得到的错误是:
(SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列'users.post_id'(SQL:select * from users where users.post_id = 1 和 users.post_id不为空)。
我正在尝试查阅包含喜欢和不喜欢两个按钮的帖子页面:
----> 表的迁移喜欢:
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id');
$table->integer('post_id');
$table->boolean('like');
$table->timestamps();
});
}
---->表用户的迁移是:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
-------->我的用户模型是:
class User extends Authenticatable
{
use Notifiable;
public function likes() {
return $this->hasMany(User::class);
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
-------------> 我的帖子模型是:
class Post extends Model
{
public $table="posts";
public function comments() {
return $this->hasMany(Comment::class)->orderBy('created_at');
}
public function likes() {
return $this->hasMany(User::class);
}
}
-----------> 我的 Like 模型是:
class Like extends Model
{
public function post() {
return $this->belongsTo(Post::class);
}
public function user() {
return $this->belongsTo(User::class);
}
-------------我的评论模型是:
class Comment extends Model
{
protected $fillable = [
'username', 'body', 'post_id'
];
public function post() {
return $this->belongsTo(Post::Class);
}
}
----> 我在刀片 Post.blade.php 中调用变量的代码部分是:
@php
$like_count = 0;
$dislike_count = 0;
@endphp
@foreach ($post->likes as $like)
@php
if($like->like == 1)
{
$like_count++;
}
if($like->like == 0)
{
$dislike_count++;
}
@endphp
@endforeach
<button type="button" class="btn btn-success">Like <i class="fa fa-
thumbs-up"></i><b> {{ $like_count }} </b>
</button>
<button type="button" class="btn btn-danger">Dislike <i class="fa fa-
thumbs-down"></i> <b> {{ $dislike_count }} </b>
</button>
我根据user.id和post.id手动在表likes中插入了一些随机数,我变成like=1
【问题讨论】:
-
什么函数或哪一行触发了这个错误?您的 users 表没有
post_id列,因此导致 SQL 错误。我认为关系设置不正确。 -
您好,您认为我应该在用户表中添加一个名为 post_id 的新列作为外键来解决这个问题吗?
-
你的关系搞砸了,你的 Post 模型的 likes 方法应该返回 $this->hasMany(Like::class, 'id', 'post_id') 并确保你的 likes 表有一个post_id 列
-
嗨@KhanShahrukh,谢谢您的帮助,错误消失了,但是每当我按下其中任何一个按钮时,按钮似乎都不会增加,似乎没有任何功能,没有任何反应,有什么建议吗?
-
在返回视图之前通过返回 $post 集合来查看控制器中的结果,很可能你会看到一个 json 对象作为结果并可以判断发生了什么
标签: laravel laravel-5 laravel-4