dousheng3364 2017-01-10 11:02
浏览 54

无法通过Laravel 5.3中的show方法创建数据

I am working on notifications I have 2 tables: one is notify and the other is notify_status. Through notify I am showing data like title and description and in notify_status I have field read_status which is by default 0. After I show it I want to change it to 1. I also have notify_id in it as a foreign key. This is my show method:

public function show($id)
{
    $notify        = Notify::find($id);
    $notify_status = NotifyStatus::where('notify_id', $id)->get();

    $user_data['read_status'] = 1;
    $user = NotifyStatus::create($user_data);

    return view('notify.desr')->with(compact('notify'));
}

But it isn't creating against notify_id. What should I do?

  • 写回答

2条回答 默认 最新

  • douhuan3448 2017-01-10 11:10
    关注

    Your models should define the following relationships:

    class Notify extends Model
    {
        public function setAsRead()
        {
            $this->status->read_status = 1
            $this->status->save();
        }
    
        public function wasRead()
        {
            return (bool) $this->status->read_status;
        }
    
        public function status()
        {
            return $this->hasOne(NotifyStatus::class);
        }
    }
    
    class NotifyStatus extends Model
    {
        public function notify()
        {
            return $this->belongsTo(Notify::class);
        }
    }
    

    Take a look at Laravel Eloquent Relationships for further reading.

    In your controller you can use it like:

    $notify = Notify::find($id);
    
    $notify->status->read_status = 1;
    $notify->status->save();
    
    return view('notify.desr')->with(compact('notify'));
    

    Or you can simply create a new method to set the new status (take a look at first method of Notify class):

    $notify = Notify::find($id);
    
    $notify->setAsRead();
    
    return view('notify.desr')->with(compact('notify'));
    
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c