我想使用这样的if else
语句:
@foreach ($comments as $comment)
<tr>
<td>
@if (is_null($ourcar))
<form method="POST" action="/comments/{{ $comment->id }}/ourcars">
{{ csrf_field() }}
<button type="submit" class="btn btn-xs btn-primary">Our cars</button>
</form>
@else
<p>saved</p>
@endif
</td>
</tr>
@endforeach
这是我的控制者:
public function browse(Request $request, CommentFilters $filters)
{
$lot_id = Comment::where('lot_id')->get();
$ourcar = OurCar::where('lot_id', '=', $lot_id)->first();
$comments = Comment::filter($filters)->orderBy('lot_date', 'desc')->paginate(30)->appends($request->all());
return view('comments.browse', compact(
'comments',
'ourcar'
));
}
我的数据库结构是:
comments table: id, lot_id,
ourcars table: id, lot_id
我的模特: 评论:
public function OurCar()
{
return $this->hasMany(OurCar::class);
}
OurCars:
public function Comment()
{
return $this->belongsTo(Comment::class);
}
OurCars迁移:
Schema::create('ourcars', function (Blueprint $table) {
$table->engine = 'MyISAM';
$table->increments('id');
$table->integer('lot_id')->unsigned();
和评论相同
我想要做的是检查lot_id是否已存在于“ourcars”表中。如果存在,则返回该车已经保存的消息。如果没有,比回声形式。
使用我的代码我有这个错误:
SQLSTATE [HY000]:常规错误:2031(SQL:select * from
ourcars
lot_id
=?限制1)
有人可以向我推荐更好的解决方案吗?
答案 0 :(得分:1)
您收到此消息的原因是因为get
方法将返回一个数组,在这种情况下,它将带来表comment
的所有行,并且至少需要1个参数才能运行。
$lot_id = Comment::where('lot_id')->get(); //
同时将模型更改为
public function OurCar()
{
return $this->hasMany('App\Comment');
}
这个
public function Comment()
{
return $this->belongsTo('App\OurCar');
}
这是一个关于如何根据代码执行此操作的示例。
将lot_id
传递到request
public function browse(Request $request, CommentFilters $filters)
{
$ourcar = OurCar::where('lot_id',$request->lot_id)->first();
$comments = Comment::filter($filters)->orderBy('lot_date', 'desc')->paginate(30)->appends($request->all());
return view('comments.browse')->with('ourcar',$ourcar)->with('comments',$comments);
}
这里是视图
@foreach ($comments as $comment)
<tr>
<td>
@if ($ourcar->lot_id != $comment->lot_id)
<form method="POST" action="/comments/{{ $comment->id }}/ourcars">
{{ csrf_field() }}
<button type="submit" class="btn btn-xs btn-primary">Our cars</button>
</form>
@else
<p>saved</p>
@endif
</td>
</tr>
@endforeach