【问题标题】:getting trouble when updating specific column values in where I used php implode method is not updating properly在我使用 php implode 方法更新特定列值时遇到问题没有正确更新
【发布时间】:2018-11-20 20:11:28
【问题描述】:

我有一个表 questions 在其中列 answerid 值类似于 1,2,3,4,5,6,7,8,9,10 。现在,当我要从 answers 表中删除 answer 时,我想更新 questions 表。假设,我要从answers 表中删除5 号码答案,并从questions 表中删除这个5 号码。但是当我这样做时,questions 表正在像这样更新-[{"answerid":"1,2,3,4,6,7,8,9,10"}] 而我想像 1,2,3,4,6,7,8,9,10 一样更新。我尝试了这样的方法-

public function deleteAnswer($id)
{
    $questionId = DB::table('answers')->where('id', $id)->get(['questionid']);
    $qid = $questionId[0]->questionid;
    $questionAns = DB::table('questions')->where('id', $qid)->get(['answerid']);

    $ansId = explode(",",$questionAns);
    //dd($ansId);


    while ($aid = current($ansId)) {
        if ($aid == $id) {
            $offset =  key($ansId);
        }
        next($ansId);
    }
   unset($ansId[$offset]);
    $implodeAnsIds = implode(",",$ansId);

   DB::table('questions')->where('id', $qid)->update([
        'answerid' => $implodeAnsIds,
   ]);

   return 'done';

}

【问题讨论】:

  • 改写标题——没意义

标签: php arrays laravel explode implode


【解决方案1】:

查询构建器上的get() 方法将始终返回一个集合。但是,您需要一个属性。

解决方案是pluck() answerid 列并选择第一行。这只会选择您需要的属性。

$questionAns = DB::table('questions')->where('id', $qid)->pluck('answerid')->first();

【讨论】:

  • 非常感谢,先生。我得到了预期的结果。
  • @RashedHasan 您可能想接受答案,因为它解决了您的问题。
猜你喜欢
  • 2019-07-22
  • 1970-01-01
  • 2014-06-13
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
相关资源
最近更新 更多