我们接着上一节一对一模型关系,继续学习laravel9框架一对多的关系,举个例子:
一个客户可能对应多个订单,这种是一对多关系。现在我们来准备一个订单表,执行命令:
php artisan make:migration create_orders_table
在2022_08_29_084031_create_orders_table.php中添加:
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->string('order_name');//订单名称
$table->integer('c_id');//关联客户ID
$table->timestamps();
});
}
执行迁移命令:php artisan migrate
对应数据表orders,然后添加一些数据:
通过执行命令 :php artisan make:model Orders
,新建Orders模型
在模型中添加:
protected $table = "orders";
public $timestamp = false;
在Clients.php中添加:
//一对多的关系
public function orders(){
return $this->hasMany('App\Models\Orders','c_id','id');
}
//一对多的关系
public function test2(){
$list = $this->get();
foreach($list as $val){
echo $val->id."
".$val->client_name."
"."对应编号:".$val->num->num_name;
foreach($val->orders as $item){
echo "订单".$item->order_name.",";
}
echo "
";
}
}
在控制器ClientController中添加:
//一对多模型关系
public function oneToMany(){
$client = new Clients();
$list = $client->test2();
dd($list);
}
在路由文件web.php中添加
//一对多模型关系演示
Route::any('one-to-many',[ClientController::class,'oneToMany']);
在浏览器中打开http://127.0.0.1:8000/one-to-many,可以看到如下效果:
说明一对多的关系程序是正确的,这一节就介绍到这里了。
留言与评论(共有 0 条评论) “” |