[WITH] Sự khác biệt with() method & load() method (ok)
https://stackoverflow.com/questions/26005994/laravel-with-method-versus-load-method
Cả hai đều đạt được cùng một kết quả cuối cùng — háo hức tải một mô hình có liên quan lên mô hình đầu tiên.
Sự khác biệt chính là with() háo hức tải mô hình liên quan lên phía trước, ngay sau truy vấn ban đầu (ví dụ: all (), first () hoặc find (x));
khi sử dụng load (), trước tiên bạn chạy truy vấn ban đầu, sau đó tải quan hệ một cách háo hức vào một thời điểm nào đó sau đó.
Eager loading using with()
$users = User::with('comments')->get();
Nếu chúng tôi có 5 người dùng, hai truy vấn sau sẽ chạy ngay lập tức:
select * from `users`
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)
"Lazy" eager loading using load()
C
húng ta có thể tách hai truy vấn, trước tiên bằng cách lấy kết quả ban đầu:
$users = User::all();
select * from `users`
$users = $users->load('comments');
select * from `comments` where `comments`.`user_id` in (1, 2, 3, 4, 5)
Ví dụ 1:
C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
Use DB;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
// $this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index() {
return view('home');
}
public function test() {
$tests = User::with('comments')->get();
return view('tests')->with(compact('tests'));
}
}
C:\xampp\htdocs\wpclidemo\app\Models\User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Comment;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function comments()
{
return $this->hasMany(Comment::class);
}
}
C:\xampp\htdocs\wpclidemo\app\Models\Comment.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model {
use HasFactory;
}
C:\xampp\htdocs\wpclidemo\app\Models\User.php
<?php
namespace App\Models;
use App\Models\Comment;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function comments() {
return $this->hasMany(Comment::class);
}
}
C:\xampp\htdocs\wpclidemo\resources\views\tests.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
@foreach ($tests as $i => $test)
<p><span>{{ $i + 1 }}</span> {{ $test->name }}</p>
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection
C:\xampp\htdocs\wpclidemo\routes\web.php
<?php
use App\Http\Controllers\HomeController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', [HomeController::class, 'index'])->name('home');
Route::get('/test', [HomeController::class, 'test'])->name('test');
C:\Users\Administrator\Downloads\comments.sql
-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 11, 2022 at 06:45 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wpclidemo`
--
-- --------------------------------------------------------
--
-- Table structure for table `comments`
--
CREATE TABLE `comments` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `comments`
--
INSERT INTO `comments` (`id`, `name`, `user_id`, `created_at`, `updated_at`) VALUES
(1, 'Ipsa quia et autem sed laudantium saepe commodi. Voluptatem dignissimos et velit. Dicta itaque repellendus excepturi voluptas.', '17', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(2, 'Nihil est eum sint maiores accusantium nihil. Atque consequatur eos voluptate nulla quae et eius. Dolores sit placeat omnis porro doloribus facere magnam in. Ullam illum itaque exercitationem nam.', '14', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(3, 'Odit vel enim et eos sequi maxime molestiae. Voluptatem accusantium quisquam sunt debitis. Dolores sed labore aut non tempora quod. Veniam ipsum et blanditiis autem neque.', '19', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(4, 'Iste expedita quia tenetur incidunt facilis alias a. Ut deleniti voluptas omnis et. Rem vel hic in. Nemo voluptas cum et quaerat sit aut fugit.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(5, 'Qui voluptatem sed rerum eveniet voluptatum. Quia et nulla est fugiat. Quis ullam corrupti quaerat ad molestiae minima.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(6, 'Omnis quo autem sed similique voluptate et nulla. Numquam quam quis amet quae. Necessitatibus dolores veniam necessitatibus magnam officiis temporibus. Sunt fugiat eveniet dolorem eveniet similique.', '2', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(7, 'Recusandae perspiciatis aut iusto soluta ipsa laboriosam beatae qui. Dolores harum nesciunt est. Molestias consequatur aut in ad omnis non. Voluptatem rem placeat tenetur.', '3', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(8, 'Consectetur nihil cumque velit nobis. Voluptatem reprehenderit quaerat quis labore aliquam. Quis aut aut sit est voluptatem dolores dolore. Facilis dolor laborum omnis numquam.', '13', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(9, 'Vel harum beatae aut sunt neque sed delectus. Nemo dignissimos non repudiandae aut molestias consectetur quia. Velit distinctio et quia tenetur. Odit temporibus consectetur illum aut error officiis.', '61', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(10, 'Consequuntur deserunt qui rerum sunt sit consequatur. Sunt quisquam libero qui cupiditate dolor eveniet accusamus. Ipsum voluptatum non nihil nihil. Corrupti dolorum repudiandae voluptatem.', '81', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(11, 'Eaque dolores velit sit. Esse cupiditate nihil veniam quis provident quisquam. Numquam rerum voluptas mollitia laborum omnis. Numquam dolores enim sit alias nulla consequatur nobis.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(12, 'Quibusdam laudantium aut in omnis. Cum doloribus numquam neque sit dolorem consequatur. Debitis natus aperiam eum soluta et nulla deserunt.', '7', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(13, 'Minima placeat ipsum est provident. Necessitatibus quidem ut est facilis. Repellat vero est quibusdam voluptas. Distinctio repudiandae sunt saepe atque nam reprehenderit.', '8', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(14, 'Fugiat autem reprehenderit placeat perspiciatis eum. Quis autem voluptate atque aut ex ut. Rem ut necessitatibus explicabo.', '15', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(15, 'Amet fugit qui pariatur eum et consectetur eum. Enim qui corporis et eum est.', '31', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(16, 'Porro aliquid inventore qui et. Veritatis nulla earum sapiente sequi explicabo incidunt eos. Cupiditate excepturi qui minus laborum animi ipsum rem ducimus.', '20', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(17, 'Cupiditate consequatur dolore et molestiae alias labore voluptates. Fuga debitis ut dolorem fugit iure temporibus. Minima dolorum sunt sed sed.', '17', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(18, 'Sit nam alias commodi reiciendis aut distinctio saepe. Molestiae facere accusantium accusantium quis enim doloribus. Saepe adipisci quo quaerat.', '14', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(19, 'Laudantium modi sit reiciendis dignissimos excepturi blanditiis. Quae alias unde vel possimus laudantium. Animi molestiae libero ipsum reiciendis voluptatibus.', '13', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(20, 'Architecto ab et soluta enim. Omnis ipsa beatae animi. Officiis illum assumenda voluptas est ad eveniet.', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(21, 'Placeat et nisi magnam. Voluptatem sapiente nobis excepturi. Modi distinctio qui voluptas aut reprehenderit fugiat vel. Eveniet enim ea modi quos.', '11', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(22, 'Iste commodi et iure quaerat. Consequuntur eos assumenda illum amet consequatur culpa. Sit modi vero ut eius natus sed.', '1', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(23, 'Ratione deleniti sit qui. Sequi qui doloremque nulla. Est maxime quidem possimus molestiae eos. Molestiae rerum est quo exercitationem.', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(24, 'Ullam architecto et rerum. Aliquam rem aut dolorem possimus. Ut ex non odit aut ut esse. Sit ut corrupti sed quidem.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(25, 'Et qui quam illo expedita omnis voluptatem est. Facilis sint saepe illo non molestiae autem. Rerum perferendis qui et velit.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(26, 'Qui ipsa molestias sequi ea est. Nostrum sint est officia amet iure magnam deserunt minima. Voluptas sed aperiam ipsa at. Ipsa voluptate atque illo praesentium.', '20', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(27, 'Temporibus perferendis autem et totam. Vero eius omnis sunt et autem. Exercitationem impedit et quasi asperiores sunt repellat ut architecto.', '5', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(28, 'Illum eum culpa sit id dolorum voluptatum. Inventore impedit repellendus ut animi velit nostrum excepturi.', '8', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(29, 'Quidem ut voluptatem voluptatum molestiae. Id culpa voluptatibus et velit veritatis dignissimos qui molestiae. Unde quas ut ex sit odit laborum repellendus. Laudantium non ex odit veritatis.', '51', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(30, 'Cumque a voluptates doloribus quo aut aut. Ex et velit quisquam esse.', '61', '2022-08-10 02:28:59', '2022-08-10 02:28:59');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `comments`
--
ALTER TABLE `comments`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `comments`
--
ALTER TABLE `comments`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C:\Users\Administrator\Downloads\users.sql
-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 11, 2022 at 06:46 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wpclidemo`
--
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`email_verified_at` timestamp NULL DEFAULT NULL,
`password` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `name`, `email`, `email_verified_at`, `password`, `remember_token`, `created_at`, `updated_at`) VALUES
(1, 'Pham Tuong', 'phamngoctuong1805@gmail.com', NULL, '$2y$10$zva/QHa2tWYiFfIyG37d4u5fvhdufmfZrAbQ6CkAknpfMuelzV08m', 'Svg4BGthZbwkBD6UZOm1ROdMuigzBAQUHNvB8xeJFnI2w0FU6CHspVK8Nurr', '2020-07-15 01:36:35', '2022-08-10 01:36:35'),
(2, 'Raphael Frami', 'rafaela03@example.net', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'N8YIabcOeF', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(3, 'Colton Howell', 'silas.deckow@example.org', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'yhwkNZTgsV', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(4, 'Mr. Enos Zemlak', 'jaron.lehner@example.org', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', '3EtrebrWdN', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(5, 'Dr. Friedrich Daugherty II', 'bartholome.monahan@example.com', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'wX3i8BX0Au', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(6, 'Kirk Schneider', 'dvandervort@example.net', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'BsmOZzgzBV', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(7, 'Annamae Smitham', 'qbaumbach@example.com', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'G2kJhhbMsu', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(8, 'Miss Melyssa Roberts II', 'srunolfsdottir@example.com', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'lxEdyZpfJU', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(9, 'Raven Lowe', 'uwisoky@example.org', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'm9VaZs6ncK', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(10, 'Dr. Tomas Rohan PhD', 'linda27@example.com', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'Ef91tnxKVL', '2022-08-10 01:38:25', '2022-08-10 01:38:25'),
(11, 'Regan Schaefer', 'mrippin@example.com', '2022-08-10 01:38:25', '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', 'PwviCxZWiP', '2022-08-10 01:38:25', '2022-08-10 01:38:25');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `users_email_unique` (`email`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=12;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C:\Users\Administrator\Downloads\pings.sql
-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 11, 2022 at 08:55 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wpclidemo`
--
-- --------------------------------------------------------
--
-- Table structure for table `pings`
--
CREATE TABLE `pings` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `pings`
--
INSERT INTO `pings` (`id`, `name`, `user_id`, `created_at`, `updated_at`) VALUES
(1, 'Ipsa quia et autem sed laudantium saepe commodi. Voluptatem dignissimos et velit. Dicta itaque repellendus excepturi voluptas.', '17', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(2, 'Nihil est eum sint maiores accusantium nihil. Atque consequatur eos voluptate nulla quae et eius. Dolores sit placeat omnis porro doloribus facere magnam in. Ullam illum itaque exercitationem nam.', '14', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(3, 'Odit vel enim et eos sequi maxime molestiae. Voluptatem accusantium quisquam sunt debitis. Dolores sed labore aut non tempora quod. Veniam ipsum et blanditiis autem neque.', '19', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(4, 'Iste expedita quia tenetur incidunt facilis alias a. Ut deleniti voluptas omnis et. Rem vel hic in. Nemo voluptas cum et quaerat sit aut fugit.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(5, 'Qui voluptatem sed rerum eveniet voluptatum. Quia et nulla est fugiat. Quis ullam corrupti quaerat ad molestiae minima.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(6, 'Omnis quo autem sed similique voluptate et nulla. Numquam quam quis amet quae. Necessitatibus dolores veniam necessitatibus magnam officiis temporibus. Sunt fugiat eveniet dolorem eveniet similique.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(7, 'Recusandae perspiciatis aut iusto soluta ipsa laboriosam beatae qui. Dolores harum nesciunt est. Molestias consequatur aut in ad omnis non. Voluptatem rem placeat tenetur.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(8, 'Consectetur nihil cumque velit nobis. Voluptatem reprehenderit quaerat quis labore aliquam. Quis aut aut sit est voluptatem dolores dolore. Facilis dolor laborum omnis numquam.', '13', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(9, 'Vel harum beatae aut sunt neque sed delectus. Nemo dignissimos non repudiandae aut molestias consectetur quia. Velit distinctio et quia tenetur. Odit temporibus consectetur illum aut error officiis.', '61', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(10, 'Consequuntur deserunt qui rerum sunt sit consequatur. Sunt quisquam libero qui cupiditate dolor eveniet accusamus. Ipsum voluptatum non nihil nihil. Corrupti dolorum repudiandae voluptatem.', '81', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(11, 'Eaque dolores velit sit. Esse cupiditate nihil veniam quis provident quisquam. Numquam rerum voluptas mollitia laborum omnis. Numquam dolores enim sit alias nulla consequatur nobis.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(12, 'Quibusdam laudantium aut in omnis. Cum doloribus numquam neque sit dolorem consequatur. Debitis natus aperiam eum soluta et nulla deserunt.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(13, 'Minima placeat ipsum est provident. Necessitatibus quidem ut est facilis. Repellat vero est quibusdam voluptas. Distinctio repudiandae sunt saepe atque nam reprehenderit.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(14, 'Fugiat autem reprehenderit placeat perspiciatis eum. Quis autem voluptate atque aut ex ut. Rem ut necessitatibus explicabo.', '15', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(15, 'Amet fugit qui pariatur eum et consectetur eum. Enim qui corporis et eum est.', '31', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(16, 'Porro aliquid inventore qui et. Veritatis nulla earum sapiente sequi explicabo incidunt eos. Cupiditate excepturi qui minus laborum animi ipsum rem ducimus.', '20', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(17, 'Cupiditate consequatur dolore et molestiae alias labore voluptates. Fuga debitis ut dolorem fugit iure temporibus. Minima dolorum sunt sed sed.', '17', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(18, 'Sit nam alias commodi reiciendis aut distinctio saepe. Molestiae facere accusantium accusantium quis enim doloribus. Saepe adipisci quo quaerat.', '14', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(19, 'Laudantium modi sit reiciendis dignissimos excepturi blanditiis. Quae alias unde vel possimus laudantium. Animi molestiae libero ipsum reiciendis voluptatibus.', '13', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(20, 'Architecto ab et soluta enim. Omnis ipsa beatae animi. Officiis illum assumenda voluptas est ad eveniet.', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(21, 'Placeat et nisi magnam. Voluptatem sapiente nobis excepturi. Modi distinctio qui voluptas aut reprehenderit fugiat vel. Eveniet enim ea modi quos.', '11', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(22, 'Iste commodi et iure quaerat. Consequuntur eos assumenda illum amet consequatur culpa. Sit modi vero ut eius natus sed.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(23, 'Ratione deleniti sit qui. Sequi qui doloremque nulla. Est maxime quidem possimus molestiae eos. Molestiae rerum est quo exercitationem.', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(24, 'Ullam architecto et rerum. Aliquam rem aut dolorem possimus. Ut ex non odit aut ut esse. Sit ut corrupti sed quidem.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(25, 'Et qui quam illo expedita omnis voluptatem est. Facilis sint saepe illo non molestiae autem. Rerum perferendis qui et velit.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(26, 'Qui ipsa molestias sequi ea est. Nostrum sint est officia amet iure magnam deserunt minima. Voluptas sed aperiam ipsa at. Ipsa voluptate atque illo praesentium.', '20', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(27, 'Temporibus perferendis autem et totam. Vero eius omnis sunt et autem. Exercitationem impedit et quasi asperiores sunt repellat ut architecto.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(28, 'Illum eum culpa sit id dolorum voluptatum. Inventore impedit repellendus ut animi velit nostrum excepturi.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(29, 'Quidem ut voluptatem voluptatum molestiae. Id culpa voluptatibus et velit veritatis dignissimos qui molestiae. Unde quas ut ex sit odit laborum repellendus. Laudantium non ex odit veritatis.', '51', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(30, 'Cumque a voluptates doloribus quo aut aut. Ex et velit quisquam esse.', '61', '2022-08-10 02:28:59', '2022-08-10 02:28:59');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `pings`
--
ALTER TABLE `pings`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pings`
--
ALTER TABLE `pings`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Ví dụ 2.1:
C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
Use DB;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
// $this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index() {
return view('home');
}
public function test() {
$tests = User::with(['comments','pings'])->get();
return view('tests')->with(compact('tests'));
}
}
C:\xampp\htdocs\wpclidemo\resources\views\tests.blade.php
@extends('layouts.app')
@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Dashboard</div>
<div class="card-body">
@foreach ($tests as $test)
@foreach ($test->pings as $key => $res)
{{ $key }} - {{ $res->name }} <br/>
@endforeach
@endforeach
</div>
</div>
</div>
</div>
</div>
@endsection
C:\xampp\htdocs\wpclidemo\app\Models\User.php
<?php
namespace App\Models;
use App\Models\Comment;
use App\Models\Ping;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable {
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function comments() {
return $this->hasMany(Comment::class);
}
public function pings() {
return $this->hasMany(Ping::class);
}
}
C:\xampp\htdocs\wpclidemo\app\Models\Ping.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Ping extends Model {
use HasFactory;
}
Ví dụ 2.2:
C:\xampp\htdocs\wpclidemo\app\Http\Controllers\HomeController.php
<?php
namespace App\Http\Controllers;
use App\Models\User;
Use DB;
use Illuminate\Http\Request;
class HomeController extends Controller {
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
// $this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Contracts\Support\Renderable
*/
public function index() {
return view('home');
}
public function test(Request $request) {
$users = User::with(['comments', 'pings']);
if ($request->has('name')) {
$users = $users->whereHas('pings', function( $query ) use ( $request ){
$query->where('pings.name', $request->name);
})->orWhereHas('comments', function( $query ) use ( $request ){
$query->where('comments.name', $request->name);
});
}
$tests = $users->get();
return view('tests')->with(compact('tests'));
}
}
Tạo ra truy vấn sau
select * from `users` where exists (select * from `pings` where `users`.`id` = `pings`.`user_id` and `pings`.`name` = 'a123') or exists (select * from `comments` where `users`.`id` = `comments`.`user_id` and `comments`.`name` = 'a123')
C:\Users\Administrator\Downloads\pings (1).sql
-- phpMyAdmin SQL Dump
-- version 5.1.3
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 11, 2022 at 09:50 AM
-- Server version: 10.4.24-MariaDB
-- PHP Version: 7.4.29
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `wpclidemo`
--
-- --------------------------------------------------------
--
-- Table structure for table `pings`
--
CREATE TABLE `pings` (
`id` bigint(20) UNSIGNED NOT NULL,
`name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`user_id` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Dumping data for table `pings`
--
INSERT INTO `pings` (`id`, `name`, `user_id`, `created_at`, `updated_at`) VALUES
(1, 'a123', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(2, 'b123', '14', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(3, 'Odit vel enim et eos sequi maxime molestiae. Voluptatem accusantium quisquam sunt debitis. Dolores sed labore aut non tempora quod. Veniam ipsum et blanditiis autem neque.', '19', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(4, 'Iste expedita quia tenetur incidunt facilis alias a. Ut deleniti voluptas omnis et. Rem vel hic in. Nemo voluptas cum et quaerat sit aut fugit.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(5, 'Qui voluptatem sed rerum eveniet voluptatum. Quia et nulla est fugiat. Quis ullam corrupti quaerat ad molestiae minima.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(6, 'Omnis quo autem sed similique voluptate et nulla. Numquam quam quis amet quae. Necessitatibus dolores veniam necessitatibus magnam officiis temporibus. Sunt fugiat eveniet dolorem eveniet similique.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(7, 'Recusandae perspiciatis aut iusto soluta ipsa laboriosam beatae qui. Dolores harum nesciunt est. Molestias consequatur aut in ad omnis non. Voluptatem rem placeat tenetur.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(8, 'Consectetur nihil cumque velit nobis. Voluptatem reprehenderit quaerat quis labore aliquam. Quis aut aut sit est voluptatem dolores dolore. Facilis dolor laborum omnis numquam.', '13', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(9, 'Vel harum beatae aut sunt neque sed delectus. Nemo dignissimos non repudiandae aut molestias consectetur quia. Velit distinctio et quia tenetur. Odit temporibus consectetur illum aut error officiis.', '61', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(10, 'Consequuntur deserunt qui rerum sunt sit consequatur. Sunt quisquam libero qui cupiditate dolor eveniet accusamus. Ipsum voluptatum non nihil nihil. Corrupti dolorum repudiandae voluptatem.', '81', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(11, 'Eaque dolores velit sit. Esse cupiditate nihil veniam quis provident quisquam. Numquam rerum voluptas mollitia laborum omnis. Numquam dolores enim sit alias nulla consequatur nobis.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(12, 'Quibusdam laudantium aut in omnis. Cum doloribus numquam neque sit dolorem consequatur. Debitis natus aperiam eum soluta et nulla deserunt.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(13, 'Minima placeat ipsum est provident. Necessitatibus quidem ut est facilis. Repellat vero est quibusdam voluptas. Distinctio repudiandae sunt saepe atque nam reprehenderit.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(14, 'Fugiat autem reprehenderit placeat perspiciatis eum. Quis autem voluptate atque aut ex ut. Rem ut necessitatibus explicabo.', '15', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(15, 'Amet fugit qui pariatur eum et consectetur eum. Enim qui corporis et eum est.', '31', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(16, 'Porro aliquid inventore qui et. Veritatis nulla earum sapiente sequi explicabo incidunt eos. Cupiditate excepturi qui minus laborum animi ipsum rem ducimus.', '20', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(17, 'Cupiditate consequatur dolore et molestiae alias labore voluptates. Fuga debitis ut dolorem fugit iure temporibus. Minima dolorum sunt sed sed.', '17', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(18, 'Sit nam alias commodi reiciendis aut distinctio saepe. Molestiae facere accusantium accusantium quis enim doloribus. Saepe adipisci quo quaerat.', '14', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(19, 'Laudantium modi sit reiciendis dignissimos excepturi blanditiis. Quae alias unde vel possimus laudantium. Animi molestiae libero ipsum reiciendis voluptatibus.', '13', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(20, 'Architecto ab et soluta enim. Omnis ipsa beatae animi. Officiis illum assumenda voluptas est ad eveniet.', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(21, 'Placeat et nisi magnam. Voluptatem sapiente nobis excepturi. Modi distinctio qui voluptas aut reprehenderit fugiat vel. Eveniet enim ea modi quos.', '11', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(22, 'Iste commodi et iure quaerat. Consequuntur eos assumenda illum amet consequatur culpa. Sit modi vero ut eius natus sed.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(23, 'Ratione deleniti sit qui. Sequi qui doloremque nulla. Est maxime quidem possimus molestiae eos. Molestiae rerum est quo exercitationem.', '10', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(24, 'Ullam architecto et rerum. Aliquam rem aut dolorem possimus. Ut ex non odit aut ut esse. Sit ut corrupti sed quidem.', '18', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(25, 'Et qui quam illo expedita omnis voluptatem est. Facilis sint saepe illo non molestiae autem. Rerum perferendis qui et velit.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(26, 'Qui ipsa molestias sequi ea est. Nostrum sint est officia amet iure magnam deserunt minima. Voluptas sed aperiam ipsa at. Ipsa voluptate atque illo praesentium.', '20', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(27, 'Temporibus perferendis autem et totam. Vero eius omnis sunt et autem. Exercitationem impedit et quasi asperiores sunt repellat ut architecto.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(28, 'Illum eum culpa sit id dolorum voluptatum. Inventore impedit repellendus ut animi velit nostrum excepturi.', '12', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(29, 'Quidem ut voluptatem voluptatum molestiae. Id culpa voluptatibus et velit veritatis dignissimos qui molestiae. Unde quas ut ex sit odit laborum repellendus. Laudantium non ex odit veritatis.', '51', '2022-08-10 02:28:59', '2022-08-10 02:28:59'),
(30, 'Cumque a voluptates doloribus quo aut aut. Ex et velit quisquam esse.', '61', '2022-08-10 02:28:59', '2022-08-10 02:28:59');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `pings`
--
ALTER TABLE `pings`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `pings`
--
ALTER TABLE `pings`
MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=31;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Last updated