Ví dụ về eloquent without() và withOnly() trong laravel.

Hello mọi người, Bài viết này mình sẽ chia sẻ cách sử dụng phương thức eloquent without() và withonly() trong laravel 8. Các bạn hãy theo dõi các ví dụ bên dưới để hiểu hơn về cách sử dụng của 2 phương thức này nhé. Đầu tiên mình sẽ tạo 3 tables với dữ liệu

Hello mọi người,
Bài viết này mình sẽ chia sẻ cách sử dụng phương thức eloquent without() và withonly() trong laravel 8.
Các bạn hãy theo dõi các ví dụ bên dưới để hiểu hơn về cách sử dụng của 2 phương thức này nhé.
Đầu tiên mình sẽ tạo 3 tables với dữ liệu demo như bên dưới.
table users

table payments

table countries

Tiếp theo trong Model User mình sẽ tạo relationships cho 3 table users, payments, countries như bên dưới.
app/Models/User.php

<?phpnamespaceAppModels;useIlluminateContractsAuthMustVerifyEmail;useIlluminateDatabaseEloquentFactoriesHasFactory;useIlluminateFoundationAuthUseras Authenticatable;useIlluminateNotificationsNotifiable;useLaravelSanctumHasApiTokens;classUserextendsAuthenticatable{useHasApiTokens, HasFactory, Notifiable;protected$with=['payments','country'];//đoạn này sẽ tự động thêm điều kiện with() vào câu query khi select dữ liệu từ bảng userspublicfunctionpayments(){return$this->hasMany(Payment::class);}publicfunctioncountry(){return$this->belongsTo(Country::class);}}

Ví dụ sử dụng query lấy tất cả dữ liệu từ bảng users

Hãy thêm code bên dưới vào trong controller như bên dưới.
app/Http/Controllers/UserController.php

<?phpnamespaceAppHttpControllers;useAppModelsUser;classUserControllerextendsController{publicfunctionindex(){$users=User::get()->toArray();dd($users);}}

Output:

array:2 [▼
  0 => array:11 [▼
    "id" => 1
    "name" => "user1"
    "email" => "[email protected]"
    "country_id" => 1
    "password" => "123456"
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
    "payments" => array:1 [▼
      0 => array:5 [▼
        "id" => 1
        "user_id" => 1
        "total_money" => 14000
        "created_at" => "2021-12-30T16:51:53.000000Z"
        "updated_at" => null
      ]
    ]
    "country" => array:4 [▼
      "id" => 1
      "name" => "Viet Nam"
      "created_at" => "2021-12-31T13:35:46.000000Z"
      "updated_at" => null
    ]
  ]
  1 => array:11 [▼
    "id" => 2
    "name" => "user2"
    "email" => "[email protected]"
    "country_id" => 2
    "password" => "123456"
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
    "payments" => array:1 [▼
      0 => array:5 [▼
        "id" => 2
        "user_id" => 2
        "total_money" => 20000
        "created_at" => "2021-12-30T16:51:53.000000Z"
        "updated_at" => null
      ]
    ]
    "country" => array:4 [▼
      "id" => 2
      "name" => "Thai Lan"
      "created_at" => "2021-12-31T13:35:46.000000Z"
      "updated_at" => null
    ]
  ]
]

Ví dụ sử dụng phương thức without()

app/Http/Controllers/UserController.php

<?phpnamespaceAppHttpControllers;useAppModelsUser;classUserControllerextendsController{publicfunctionindex(){$users=User::without("payments")->get()->toArray();dd($users);}}

Output:

array:2 [▼
  0 => array:10 [▼
    "id" => 1
    "name" => "user1"
    "email" => "[email protected]"
    "country_id" => 1
    "password" => "123456"
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
    "country" => array:4 [▼
      "id" => 1
      "name" => "Viet Nam"
      "created_at" => "2021-12-31T13:35:46.000000Z"
      "updated_at" => null
    ]
  ]
  1 => array:10 [▼
    "id" => 2
    "name" => "user2"
    "email" => "[email protected]"
    "country_id" => 2
    "password" => "123456"
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
    "country" => array:4 [▼
      "id" => 2
      "name" => "Thai Lan"
      "created_at" => "2021-12-31T13:35:46.000000Z"
      "updated_at" => null
    ]
  ]
]

Ví dụ sử dụng phương thức withOnly()

app/Http/Controllers/UserController.php

<?phpnamespaceAppHttpControllers;useAppModelsUser;classUserControllerextendsController{publicfunctionindex(){$users=User::withOnly("payments")->get()->toArray();dd($users);}}

Output:

array:2 [▼
  0 => array:10 [▼
    "id" => 1
    "name" => "user1"
    "email" => "[email protected]"
    "country_id" => 1
    "password" => "123456"
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
    "payments" => array:1 [▶]
  ]
  1 => array:10 [▼
    "id" => 2
    "name" => "user2"
    "email" => "[email protected]"
    "country_id" => 2
    "password" => "123456"
    "remember_token" => null
    "is_active" => 1
    "created_at" => null
    "updated_at" => null
    "payments" => array:1 [▶]
  ]
]

Hy vọng bài viết này sẽ giúp ích cho bạn!

Nguồn: viblo.asia

Bài viết liên quan

7 Cách Tăng Tốc Ứng Dụng React Hiệu Quả Mà Bạn Có Thể Làm Ngay

React là một thư viện JavaScript phổ biến trong việc xây dựng giao diện người d

Trung Quốc “thả quân bài tẩy”: hàng loạt robot hình người!

MỘT CUỘC CÁCH MẠNG ROBOT ĐANG HÌNH THÀNH Ở TRUNG QUỐC Thượng Hải, ngày 13/5 –

9 Mẹo lập trình Web “ẩn mình” giúp tiết kiệm hàng giờ đồng hồ

Hầu hết các lập trình viên (kể cả những người giỏi) đều tốn thời gian x

Can GPT-4o Generate Images? All You Need to Know about GPT-4o-image

OpenAI‘s GPT-4o, introduced on March 25, 2025, has revolutionized the way we create visual con