模型關聯一對多

yaoxs發表於2021-03-31

資料庫表

# 使用者表
CREATE TABLE `user_test` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

# 訂單表
CREATE TABLE `orders` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_test_id` int(10) unsigned NOT NULL,
  `order_number` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
# 測試資料
INSERT INTO `user_test` (`id`, `name`, `created_at`, `updated_at`) VALUES ('1', 'yaoxs', '2021-03-30 23:54:46', NULL);
INSERT INTO `orders` (`id`, `user_test_id`, `order_number`, `created_at`, `updated_at`) VALUES ('1', '1', 'yaoxs的訂單編號1', NULL, NULL);
INSERT INTO `orders` (`id`, `user_test_id`, `order_number`, `created_at`, `updated_at`) VALUES ('2', '1', 'yaoxs的訂單編號2', NULL, NULL);
INSERT INTO `orders` (`id`, `user_test_id`, `order_number`, `created_at`, `updated_at`) VALUES ('3', '1', 'yaoxs的訂單編號3', NULL, NULL);

模型

app\Models

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserTest extends Model
{
    protected $table = 'user_test';
    /**
     * 獲取該使用者的所有訂單
     */
    public function orders()
    {
        return $this->hasMany('App\Models\Comment');
    }
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
    protected $table = 'orders';
}

路由

use Illuminate\Support\Facades\Route;
use App\Models\UserTest;
// 編寫獲取指定使用者所有訂單的方法
Route::get('/get-user-order/{user:id}', function(UserTest $user){
    // 使用者ID不應該由使用者輸入這裡只是為了演示
    dd($user->orders()->select('order_number')->get()->toArray());die;
});

訪問:127.0.0.1:8000/get-user-order/1

array:3 [0 => array:1 ["order_number" => "yaoxs的訂單編號1"
  ]
  1 => array:1 ["order_number" => "yaoxs的訂單編號2"
  ]
  2 => array:1 ["order_number" => "yaoxs的訂單編號3"
  ]
]
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章