gpt4 book ai didi

php - Laravel 如何在查询中传递多个值

转载 作者:行者123 更新时间:2023-11-28 23:23:54 26 4
gpt4 key购买 nike

我正在尝试使用 laravel 5.2 查询在我的表中创建一个新行。

我的“answers”表有 5 列-> answer_id (auto_inc), people_id(与 Auth::id 相同), question_id('Integer'), answer(input field), created_at(timestamp())

应答 Controller 文件:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;
use App\Http\Requests;

class answerController extends Controller
{
public function store(Requests\answerAddRequest $request)
{
Auth::user()->questions('question_id')->answers()->create($request->all());
}
}

回答模型类

class answers extends Model
{
protected $table='answers';
protected $fillable='answer';
protected $primaryKey='answer_id';
public function setUpdatedAtAttribute($value) {}
public function User()
{
return $this->belongsTo('App\User');
}
public function questions()
{
return $this->belongsTo('App\questions','people_id');
}
}

我无法在 answers 表中添加新行,因为我无法理解如何在表中传递 question_id

问题模型类

class questions extends Model
{
protected $table='questions';
protected $primaryKey='question_id';
protected $fillable = [
'question', 'created_at','details'
];
//protected $hidden=['question_id'];
public function setUpdatedAtAttribute($value) {}
public function User() {
return $this->belongsTo('App\User');
}
public function answers()
{
return $this->hasMany('App\answers','answer_id');
}
public function scopefetchQuestions($query) {
return $query->select('question','question_id')->where('people_id','=',Auth::id())->get();
}
}

它在当前代码中抛出这个错误:

BadMethodCallException in Builder.php line 2405:
Call to undefined method Illuminate\Database\Query\Builder::answers()

我该如何解决?

最佳答案

请试试这个:

class answerController extends Controller
{
public function store(Requests\answerAddRequest $request)
{
$answer = App\Answer::create($request->all());
Auth::user()->questions()->where('question_id', $request->get('question_id'))->first()->answers()->save($answer);
}
}

同时向$fillable 数组添加外键 https://laravel.com/docs/5.2/eloquent#inserting-and-updating-models https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models

关于php - Laravel 如何在查询中传递多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40267911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com