【问题标题】:Get value from select field and compare against database从选择字段中获取值并与数据库进行比较
【发布时间】:2019-08-15 19:34:54
【问题描述】:

我需要什么:

使用下面的 DB 列clay_plan_type

+----+------------------+
| id | clay_plan_type   |
+----+------------------+
|  5 | Single Shooter   |
|  6 | Lunch Sponsor    |
|  7 | Beverage Sponsor |
+----+------------------+

如果我的选择字段的值与clay_plan_type 中的值匹配,我想禁用表单中的选择选项

查看示例:

@if ($sponsortype === "Beverage Sponsor")
<option value="" disabled>Beverage Sponsor: SOLD OUT</option>
@else
<option value="Beverage Sponsor">Beverage Sponsor: $250</option>
@endif
etc...

控制器示例:

$sponsortype = DB::table('clay_shoots')->select('clay_plan_type')->get();
return view('clayshoot.sponsorform',compact('sponsortype'));

当我dd($sponsortype); 我得到以下信息:

Collection {#855 ▼
  #items: array:3 [▼
    0 => {#801 ▼
      +"clay_plan_type": "Single Shooter"
    }
    1 => {#802 ▼
      +"clay_plan_type": "Lunch Sponsor"
    }
    2 => {#803 ▼
      +"clay_plan_type": "Beverage Sponsor"
    }
  ]
}

在视图中运行if statement 时没有出现错误,但没有得到正确的结果。它充当 `if 语句不存在。

所以我尝试添加 $sponsortype-&gt;clay_plan_type 并得到错误:

此集合实例上不存在属性 [clay_plan_type]。

如果我在 foreach loop 中运行,这在视图中有效,但我在选择字段中获得了同一项目的多次重复。 (见下图)

@foreach($sponsortype as $st)
  @if ($st->clay_plan_type == "Beverage Sponsor" )
    YUP
  @else
    NOPE
  @endif
@endforeach
// OUTPUT: NOPE NOPE YUP ("Beverage Sponsor" is the last record in the table)

希望我以您理解的方式解释这一点。如果您需要更多信息,请告诉我。任何帮助弄清楚这一点将不胜感激。

【问题讨论】:

  • $sponsortype 是一个集合,因此您必须像在上一个示例中那样在 @foreach 中对其进行迭代。一切似乎都运行良好。您应该将&lt;input&gt; 设置为YUP 和NOPE,它会起作用。这里有什么问题?
  • 我有 4 个计划:Bev、早餐、午餐和单身。我在clay_plan_type 列中将有多达 24 个单曲,当我循环它时,我最终会在我的选择字段中获得 24 个 Bev、早餐和午餐选项。那是我的问题。
  • 不知道我是否理解。可以显示clay_plan_type的内容吗?
  • @DamianDziaduch 内容是数据库和模具转储中的内容。
  • @DamianDziaduch 我在 Beverage Sponsor 选项文件中添加了 foreach 循环的图像,以帮助您展示我的困境。

标签: php laravel


【解决方案1】:

您可以使用contains 收集方法并传递一个键/值对。

来自docs:

您还可以将键/值对传递给 contains 方法,该方法 将确定给定对是否存在于集合中:

$collection = collect([
    ['product' => 'Desk', 'price' => 200],
    ['product' => 'Chair', 'price' => 100],
]);

$collection->contains('product', 'Bookcase');

// false

在你的情况下:

@if ($sponsortype->contains("clay_plan_type", "Beverage Sponsor"))
    <option value="" disabled>Beverage Sponsor: SOLD OUT</option>
@else
    <option value="Beverage Sponsor">Beverage Sponsor: $250</option>
@endif

【讨论】:

  • 没有foreach loop 就完美了。正是我需要的!谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-31
  • 2018-04-18
相关资源
最近更新 更多