4

我正在尝试在我的数据表中放置一个 foreach 循环,但它不会工作,PS 如果我删除 foreach 一切都已经正常工作,附上我的代码

$Product = Product::query();
$colors   = Color::all();

return Datatables::eloquent($Product)

    ->addColumn('category_name', function($row) {

        $category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
        return $category;

    })

    ->addColumn('add_color', function($row) {

        $return = 
            '<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
            <input type="hidden" name= "product_id" value="' . $row->id . '">

            <div class="form-group">
            <select name="color_id" class="form-control" required autofocus>
                    '.foreach ($colors as $color){.' 
                    <option value="test">test</option>'.}.'
            </select>
            </div>';

        return $return;

});
4

2 回答 2

5

那行不通,您将 a 附加foreach到 astring

您可以做的是foreach首先准备要附加在该字符串中的项目。

例如,

<option>something</option>
<option>something more</option>

在设置之前$returnforeach

->addColumn('add_color', function($row) {

    $options = ''
    // here we prepare the options
    foreach ($colors as $color) {
        $options .= '<option value="test">$color</option>';
    }

    $return = 
       '<form class="form-inline" method="post" action="/procurement/add product" style="max-width: 170px;">
        <input type="hidden" name= "product_id" value="'.$row->id.'">

        <div class="form-group">
            <select name="color_id" class="form-control" required autofocus>' . $options . '</select>
        </div>';

    return $return;

})
于 2017-09-22T02:17:51.340 回答
4

您需要在返回之外执行 foreach 。然后您也不需要use或导入$color数据表中的变量。像这样的东西..

$Product = Product::query();
$colors   = Color::all();

return Datatables::eloquent($Product)

->addColumn('category_name', function($row) {

    $category = Category::select('name')->where('id', $row->category_id )->pluck('name')->toArray();
    return $category;

})

->addColumn('add_color', function($row) use ($colors)  {
        $options = '';
        foreach ($colors as $color) {
            $options .= '<option value="test">$color</option>';
        }

    $return = 
        '<form class="form-inline" method="post" action="/procurement/add-product" style="max-width: 170px;">
        <input type="hidden" name= "product_id" value="' . $row->id . '">

        <div class="form-group">
        <select name="color_id" class="form-control" required autofocus>
        </select>
        </div>';

    return $return;

});
于 2017-09-22T02:38:13.747 回答