Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php ajax成功了,但laravel没有插入到数据库中_Php_Jquery_Ajax_Laravel - Fatal编程技术网

Php ajax成功了,但laravel没有插入到数据库中

Php ajax成功了,但laravel没有插入到数据库中,php,jquery,ajax,laravel,Php,Jquery,Ajax,Laravel,我对我的上票/下票制度感到非常困难。ajax执行success函数,但是laravel不会向数据库中插入任何内容。。我不知道我做错了什么。我的AJAX: $('[data-value]').on('click', function () { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); var $this

我对我的上票/下票制度感到非常困难。ajax执行success函数,但是laravel不会向数据库中插入任何内容。。我不知道我做错了什么。我的AJAX:

$('[data-value]').on('click', function () {
  $.ajaxSetup({
      headers: {
          'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
      }
  });
  var $this = $(this);
  var post_id = $this.data('id');
  var votetype = $this.data('value');
  $.ajax({
    type:"POST",
    url:'/post/' + post_id + '/vote/' + votetype,
    success:vote(post_id,votetype)
  });
  // vote(post_id,votetype);
  });
我的路线:

Route::post('/post/{id}/vote/{vote}', 'PostController@vote');
My laravel投票功能:

  public function vote($id,$vote)
    {
      //TODO: refactor this..
      $username = Session::get('username');
      $id = Post::find($id);
      $uservote = PostVotes::where('id',$id)->where('username',$username)->first();
      if($uservote->count())
      {
        $votetype = $uservote->vote;
        if($votetype === $vote)
        {
            $uservote->delete();
        } else {
          Vote::updateOrCreate(
             ['vote' => $votetype],
             ['vote' => $vote]
           );
        }
      } else {
        $uservote = new PostVotes;
        $uservote->vote = $vote;
        $uservote->username = $username;
        $uservote->id = $id;
        $uservote->save();
      }
    }
我不知道这是否必要,但这是我的迁移

class CreatePostVotesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('post_votes', function (Blueprint $table) {
            $table->integer('id');
            $table->string('username',50);
            $table->integer('vote');

        });
    }
}

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id')->unique;
            $table->string('title',80);
            $table->string('username',50);
            $table->integer('score');
            $table->timestamp('created_at');
            $table->string('image',512);
        });
    }
 }
关系:(Post.php):

postdowes.php:

public function post()
    {
      return $this->belongsTo(Post::class,'id');
    }

只有在数据成功插入数据库后,才从服务器返回OK


服务器可能返回OK,但数据尚未实际插入数据库。jquery success函数将在没有实现系统预期功能的情况下执行

我确信其中一个问题是:

$id = Post::find($id);
/*
 * you are passing instance of the Post model or null into where('id', $id) 
 * predicate, instead of the id of the post
 */
$uservote = PostVotes::where('id',$id)->where('username',$username)->first();
您可以尝试更改此设置:

$post = Post::find($id);
$uservote = PostVotes::where([
        'id' => $post->id,
        'username' => $username,
    ])
    ->first();
$uservote->id = $id;
因为您正在将模型
Post
(或
null
)的实例传递到您的条件中,如果
Post::find($id)
不返回任何内容,则将其传递到Post
id
属性中

添加:

在使用
$uservote
之前,您应该检查
$uservote

$uservote = PostVotes::where([
        'id' => $post->id,
        'username' => $username,
    ])
    ->first();

// $uservote is empty, you should create new instance of the PostVotes model
if( empty($uservote)){
}
此外,如果此
id
是帖子的id,您还可以传递函数
vote
的参数
$id

$uservote = PostVotes::where([
        'id' => $id, // <-- use $id, if $id is the post id
        'username' => $username,
    ])
    ->first();
关于这一点:

$uservote->id = $post->id;
在接受我对代码的建议后,当
$post=post::find($id)

顺便说一下,为了更好的可读性,如果您想将文章的id存储在此属性中,您应该将模型的
id
属性
Vote
重命名为
post\u id
。通常,名为
id
的字段用作具有自动递增属性的表主键

还可以查看
/storage/logs/laravel.log
文件,从中可以找到有关错误的更多信息

添加#2

你应该得到这样的东西:

public function vote($id, $vote)
{
    //TODO: refactor this..
    $username = Session::get('username');
    $post = Post::find($id);

    if( empty($post) ){
        abort(404, 'Cannot find post');
    }

    $uservote = PostVotes::where([
            'id' => $post->id,
            'username' => $username,
        ])
        ->first();

    // replace $uservote->count() with !empty($userwote), because you cannot call count() nethod from null
    if (!empty($uservote)) {
        $votetype = $uservote->vote;
        if ($votetype === $vote) {
            $uservote->delete();
        } else {
            Vote::updateOrCreate(
                ['vote' => $votetype], ['vote' => $vote]
            );
        }
    } else {
        $uservote = new PostVotes();
        $uservote->vote = $vote;
        $uservote->username = $username;
        $uservote->id = $post->id; // <!-- probably replace `id` field name on `post_id`
        $uservote->save();
    }
}
公共功能投票($id,$vote)
{
//TODO:重构此。。
$username=Session::get('username');
$post=post::find($id);
如果(空($员额)){
中止(404,“找不到post”);
}
$uservote=PostVotes::其中([
'id'=>$post->id,
“用户名”=>$username,
])
->第一个();
//将$uservote->count()替换为!empty($userwote),因为不能从null调用count()nethod
如果(!empty($uservote)){
$votetype=$uservote->vote;
如果($votetype===$vote){
$uservote->delete();
}否则{
投票::更新或创建(
['vote'=>$votetype],'vote'=>$vote]
);
}
}否则{
$uservote=new PostVotes();
$uservote->vote=$vote;
$uservote->username=$username;

$uservote->id=$post->id;//您在哪里声明这个
vote(post\u id,votetype)
函数?如何关联这两个表?您应该在
post\u vots
中有一列
post\u id
table@hassan在main.js文件中..我不认为问题出在ajax上,也许我在投票函数中做错了什么(在控制器中)@Niklesh编辑了问号IDK,这是否有帮助,但在laravel.log中有一个生产错误,该错误表示调用nullI上的成员函数count()。我更新了关于下一个问题的答案。在使用之前,您应该检查
$uservote
,如果$uservote为空,则创建一个新的:
if(empty($uservote)){//create new PostVotes实例…
很抱歉,我有点困惑,我应该把if(empty($uservote))放在哪里?你能更改我的代码吗?我在答案的底部添加了可能版本的函数
vote
。我开始认为这是我的路由问题。因为如果我在url中这样做,它会显示methodnotallowedhttpexception。。
public function vote($id, $vote)
{
    //TODO: refactor this..
    $username = Session::get('username');
    $post = Post::find($id);

    if( empty($post) ){
        abort(404, 'Cannot find post');
    }

    $uservote = PostVotes::where([
            'id' => $post->id,
            'username' => $username,
        ])
        ->first();

    // replace $uservote->count() with !empty($userwote), because you cannot call count() nethod from null
    if (!empty($uservote)) {
        $votetype = $uservote->vote;
        if ($votetype === $vote) {
            $uservote->delete();
        } else {
            Vote::updateOrCreate(
                ['vote' => $votetype], ['vote' => $vote]
            );
        }
    } else {
        $uservote = new PostVotes();
        $uservote->vote = $vote;
        $uservote->username = $username;
        $uservote->id = $post->id; // <!-- probably replace `id` field name on `post_id`
        $uservote->save();
    }
}