适用于嵌套foreach的Laravel语法

时间:2017-01-29 15:07:56

标签: php laravel blade

在laravel 5或更高级别中是否有任何laravel标准或方法来实现这一点谢谢你提前

$sql = "SELECT * FROM categories";

$result = $conn->query($sql);


    if ($result->num_rows > 0) {


while ($row = $result->fetch_assoc()) {
        echo $row['category']."[";
        $sql2 = "SELECT * FROM subCategories where category_id = ".$row['id']." limit 4";
        $result2 = $conn->query($sql2);
        if ($result2->num_rows > 0) {
            while ($row2 = $result2->fetch_assoc()) {
                echo $row2['name']." ; ";
            }
        }
        echo " ]</br>";
    }
} else {
    echo "0 results";
}

2 个答案:

答案 0 :(得分:0)

是的,当然。您可以使用Laravel的Eloquent ORMModel轻松实现此目标。

首先,您必须创建两个模型并定义它们之间的关系。首先是Category模型:

<?php // Category.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

    public function subcategories()
    {
        return $this->hasMany(SubCategory::class);
    }
}

然后是SubCategory模型:

<?php // SubCategory.php
namespace App;

use Illuminate\Database\Eloquent\Model;

class SubCategory extends Model
{
    protected $table = 'subCategories';

    public function category()
    {
        return $this->belongsTo(Category::class);
    }
}

之后,它就像下面一样容易获得类别和类别下的子类别:

<?php
// get all categories
$categories = Category::all();

// get subcategories for each category
foreach($categories as $category)
{
    $subCategories = $category->subcategories();
    foreach($subCategories as $subCategory) 
    {
        echo $subCategory;
    }
}

答案 1 :(得分:0)

我同意@Muhammad Sumon Molla Selim定义Eloquent模型。但是当你按照他描述的方式进行查询时,你会面对N+1 issue。您可以Eager load来解决它。就这样做吧。

$categories = Category::with('subcategories')->get();

然后你可以像这样循环

foreach ($categories as $category) {
    foreach ($category->subcategories as $subCategory) {
        echo $subcategory;
    }
}