php - Laravel Eloquent 枢轴将变量传递给模型

标签 php mysql laravel model eloquent

我在将变量传递给 Eloquent 模型时遇到问题。我会给你举个例子 数据库:

书:

-id

-名称

用户:

-id

-名称

愿望 list :

-book_id

-user_id

现在当我拿到书的记录时。我想检查用户的愿望 list 中是否有这本书。

我有这样的关系:

书籍 Eloquent 模型:

public function wishList($userId)
{
    return $this->hasOne('App\Model\Pivot\WishList', 'comics_record_id')->where('user_id',$userId);
}

但是当我运行这段代码时,我不予思考。

图书 Controller :

$record = Book:find(1);

$record->wishList(1);

我也尝试在 Eloquent 模型中制作 setter 。 没有思考工作:(

感谢您的帮助,并对我的英语表示抱歉。

最佳答案

首先改变你与此的关系-

public function wishList()
{
return $this->hasMany('App\Model\Pivot\WishList', 'book_id', 'id');
}

那么你们的关系将会是-

$book = Book::with('wishList')->where('id',$book_id)->whereHas('wishList', function($q) use ($user_id){
       $q->where('user_id',$user_id);
})->first();

if($book){
    //show true here
}
else{
    //show false here
 }

关于php - Laravel Eloquent 枢轴将变量传递给模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48448156/

相关文章:

php - 警告 : in_array() [function. in-array]:第二个参数的数据类型错误

mysql - 选择显示第一个唯一值的行

php - laravel 更新 session 数组中的值

php - Docker:docker-compose 将文件从容器复制到主机

php - Ajax 在 laravel 上返回整个 HTML 文档

php - Laravel 实例错误

MySQL搜索并替换字段中的一些文本

PHP:如何创建一个好的 foreach 速记?

php - (403) 当我调用 Google_Service_Analytics_Profile 对象的插入时,您的项目无权访问此功能

php - 使用 PHP 处理 Follow/Followers