【问题标题】:Best way to query a model with search and pass its id into another model使用搜索查询模型并将其 id 传递给另一个模型的最佳方法
【发布时间】:2020-11-06 16:37:18
【问题描述】:

我能得到一些帮助吗?我正在尝试查询我的模型数据库作为搜索。获取结果后,我想通过表单将集合的 id 传递给另一个模型,并且我不想使用包。

到目前为止,我一直在出错。

基本上,我正在查询数据库

$services = Service::where('name' 'LIKE' Request::('input')):

但是如果我尝试通过 $servces 来查看


return view('search.result')->with($services);

它返回**非法偏移类型。 **

所以,我必须详细链接 $services 像这样:

return view('search.results')->withDetails($services);

在我的 results.blade.php 上,我有:

@foreach($details as $d) 
{{$d->name}} 
<form action="{{route('book', ['id' =>$d->id} method="POST">
<button type="submit">Book</button>
</form>
@endforeach 

这会显示服务集合

但是,如果我尝试像这样将 $d 集合的 Id 传递到 Book 模型中:

public function book($id) {
$service = Service::find($id);

//or

$service = Service::where('id', $id) ;

App\Models\Book::insert([
'service_I'd => $service->id]) ;

它告诉我这个 id 不存在 集合实例。

有人可以帮助我更好地实现这一目标吗?

【问题讨论】:

    标签: mysql sql laravel eloquent


    【解决方案1】:

    在你的行中:

    $services = Service::where('name' 'LIKE' Request::('input')):

    应该是:

    $services = Service::where('name', 'LIKE', Request::('input'))->get();
    

    或者如果你想获得相似的名字:

    $services = Service::where('name', 'LIKE','%'. Request::('input').'%')->get();
    

    在这一行:

    $service = Service::where('id', $id) ;
    

    你可以使用:

    $service = Service::firstWhere('id', $id) ;
    

    【讨论】:

    • 它返回试图获取非对象模型的属性
    • 它的 ``` $service = Service::findWhere('id', $id) ; ```
    • findWhere 没问题,但为什么不 firstWhere 呢?
    【解决方案2】:

    因此,要将返回集合的 id 传递给新模型,我必须使用

    
    ///Then, 
    
    Book::insert([
    'service_Id => $service->id]);
    
    

    非常感谢大家。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多