Bài 12: Eloquent ORM trong Laravel

Tài liệu Laravel

Bài trước mình đã giới thiệu với mọi người cách tạo Model cũng như cách cấu hình Model, nhưng chưa được ứng dụng vào thực tế ,Thì bài này mình sẽ hướng dẫn mọi người truy vấn cơ sở dữ liệu trong Model với Eloquent ORM của Laravel.

1,Cách gọi Model.

-Để gọi Model trong Controllers thì bắt buộc chúng ta phải gọi namespace của model đó trong Controllers.

  • VD: mình muốn gọi Model news trong homecontroller.
phpcopy<?php

namespace App\Http\Controllers;

use App\News;

class homecontroller extends Controller
{
   News::all();
}

Hoặc

phpcopy<?php

namespace App\Http\Controllers;

use App;

class homecontroller extends Controller
{
   App\News::all();
}

-Còn nếu muốn gọi model trong Route thì các bạn không cần gọi namespace mà các bạn có thể dùng luôn với cú pháp.

phpcopyApp\TenModel::someThing;

VD: mình muốn gọi Model news trong route.

phpcopyApp\News::all();

2, Các câu truy vấn hay dùng trong Eloquent ORM.

Chú ý: Tất cả các cú pháp dưới đây mình lấy News model Làm mẫu nhé

Lấy ra dữ liệu trong bảng.

-Lấy ra tất cả dữ liệu trong bảng.

phpcopyNews::all();

-Lấy ra một dòng dữ liệu thông qua khóa chính.

phpcopyNews::find(1);

Hoặc

phpcopyNews::take(1)->get();

-Truy vấn điều kiện.

+Bằng:

phpcopyNews::where('id', 5)->get();

+Lớn hơn, nhỏ hơn,.. (giống Query Buider)

-Chọn cột dữ liệu.

phpcopyNews::select('id', 'title')->get();

-Đếm dữ liệu.

phpcopyNews::all()->count();

Thêm dữ liệu.

phpcopy$news = new News();
$news->title = "tin tức 1";
$news->categoryId = 1;
$news->save();

-Ở trên mình đã thêm vào cột title nội dung là ‘tin tức 1’ và cột categoryId là 1.

Sửa dữ liệu.

-Ví Dụ mình muốn sửa tiêu đề của bảng news có id =1.

phpcopy$news = News::find(1);
$news->title = 'toidicode.com';
$news->save();

Hoặc

phpcopyNews::where('id', 1)->update(['title' => 'toidicode.com']);

Xóa

-Cách 1:

phpcopy$news= News::find(1);
$news->delete();

-Cách 2:

phpcopyNews::destroy(1);
//or
News::destroy(1, 2);
//or
News::destroy([1, 2, 3]);
//or
News::destroy(array(1, 2, 3));

-Trong đó: 1, 2, 3 là các id(primary) của bảng cần truy vấn.

-Cách 3:

phpcopyNews::where('id', 1)->delete();