crocodic/laravel-model

增强Laravel数据库关系,使用模型增强功能

v4.1.3 2021-03-13 11:05 UTC

README

一个替代的Laravel Eloquent。Crocodic Laravel Model使用模型、仓库和服务模式。模型是一个类,用于定义有关表列的信息。仓库是一个类,用于定义你自己的查询方法。服务是一个类,应该定义你自己的业务逻辑查询方法。

要求

Laravel / Lumen 5.* | 6.* | 7.* | 8.*

安装命令

composer require crocodic/laravel-model

LUMEN用户

安装后使用composer,然后添加以下内容到/bootstrap/app.php中的Register Service Providers部分

$app->register(\Crocodic\LaravelModel\LaravelModelServiceProvider::class);

1. 创建模型

从表创建模型
php artisan create:model foo_bar_table

为所有表创建模型
php artisan create:model

使用其他连接创建模型
php artisan create:model foo_bar_table --connection=con2

假设你有一个books表,结构如下

id (Integer) Primary Key
created_at (Timestamp)
name (Varchar) 255

它将在/app/Models/BooksModel.php创建一个新的模型类文件,以下为文件结构

<?php
namespace App\Models;

use DB;
use Crocodic\LaravelModel\Core\Model;

class BooksModel extends Model
{
    public $id;
    public $created_at;
    public $name;
}

还将创建一个新的仓库类文件和一个新的服务类文件。/app/Repositories/Books.php /app/Services/BooksService.php

你可以设置自定义连接、表和主键名称

<?php
namespace App\Models;

use DB;
use Crocodic\LaravelModel\Core\Model;

class BooksModel extends Model
{
    public $id;
    public $created_at;
    public $name;
    
    public function setConnection(){
         return "mysql";
    }

    public function setTable() {
        return "books";
    }   

    public function setPrimaryKey(){
        return "id";
    }
}

2. 在你的控制器中使用Crocodic Laravel Model类

Crocodic Laravel Model使用模型、仓库和服务模式。如果你想进行查询,请使用仓库而不是模型类。例如,在控制器类顶部插入use App\Repositories\Books;

<?php 
namespace App\Http\Controllers;

use App\Repositories\Books;

class FooController extends Controller {
    
    public function index() 
    {
        $books = Books::latest();
        return view("books", ["bookData"=>$books]);
    }
    
    public function detail($id)
    {
        $book = Books::find($id);
        return view("book_detail", ["book"=>$book]);
    }
    
    public function delete($id)
    {
        Books::deleteById($id);
        
        return redirect()->back()->with(["message"=>"Book ".$book->name." has been deleted!"]);
    }
}
?>

3. 使用具有关系的Crocodic Laravel Model类

假设你有一个用于书籍关系的categories表,如下所示

id (Integer) Primary Key
name (Varchar) 255

你的书籍结构如下

id (Integer) Primary Key
created_at (Timestamp)
categories_id (Integer)
name (Varchar) 255

现在你必须为categories表创建一个模型,你可以按照前面的步骤进行。

假设你已经创建了一个categories模型,所以请确保现在在/app/Models/中我们有两个文件

/BooksModel.php
/CategoriesModel.php

打开Books模型,并添加以下方法

    /**
    * @return App\Models\Categories
    */
    public function category() {
        return $this->belongsTo("App\Models\Categories");
    }

    // or 
    /**
    * @return App\Models\Categories
    */
    public function category() {
        return Categories::find($this->categories_id);
    }

然后打开FooController

<?php 
namespace App\Http\Controllers;

use App\Repositories\Books;

class FooController extends Controller {
    
    
    public function detail($id)
    {
        $book = Books::find($id);
        
        $data = [];
        $data['book_id'] = $book->id;
        $data['book_name'] = $book->name;
        $data['book_category_id'] = $book->category()->id;
        $data['book_category_name'] = $book->category()->name;
        
        return view("book_detail",$data);
    }
    
}
?>

正如你所看到的,现在我们可以通过使用->category()->name来获取类别名称,而不需要任何SQL查询或数据库构建器语法。你还可以递归地向下到你的关系,没有任何限制。

4. 如何将DB Builder Collection输出转换为Crocodic Laravel Model类?

你可以轻松地将简单的数据库构建器集合转换为cb模型类。

$row = DB::table("books")->where("id",1)->first();

//Cast to Crocodic Laravel Model
$model = new Books($row);

//And then you can use cb model normally
echo $model->name;

5. 如何使用Crocodic Laravel Model插入数据

你可以通过使用方法->save()轻松地插入数据,如下所示

$book = new Books();
$book->created_at = date("Y-m-d H:i:s"); //this created_at is a magic method you can ignore this
$book->name = "New Book";
$book->categories_id = 1;
$book->save();

然后如果你想获取最后插入的ID,你可以这样做

...
$book->save();
$lastInsertId = $book->id; // get the id from id property
...

5. 如何使用Crocodic Laravel Model更新数据

你可以轻松地更新数据,只需首先找到它

$book = Books::findById(1);
$book->name = "New Book";
$book->categories_id = 1;
$book->save();

5. 如何删除数据?

你可以轻松地删除数据,只需首先找到它

$book = Books::findById(1);
$book->delete();

Books::deleteById(1);

模型方法可用

/**
* Find all data by specific condition.
*/ 
$result = FooBar::findAllBy($column, $value = null, $sorting_column = "id", $sorting_dir = "desc");
// or 
$result = FooBar::findAllBy(['foo'=>1,'bar'=>2]);

/**
* Find all data without sorting
*/
$result = FooBar::findAll();

/**
* Count the records of table
*/ 
$result = FooBar::count();

/**
* Count the records with specific condition 
*/
$result = FooBar::countBy($column, $value = null);
// or
$result = FooBar::countBy(['foo'=>1,'bar'=>2]);

/**
* Find all datas and ordering the data to descending
*/
$result = FooBar::findAllDesc($column = "id");
// or simply
$result = FooBar::latest();

/**
* Find all datas and ordering the data to ascending
*/
$result = FooBar::findAllAsc($column = "id");
// or simply
$result = FooBar::oldest();

/** 
* Find/Fetch a record by a primary key value
*/
$result = FooBar::findById($id);
// or simply
$result = FooBar::find($id);

/**
* Create a custom query, and result laravel Query Builder collection
*/
$result = FooBar::where("foo","=",1)->first();
// or
$result = FooBar::table()->where("foo","=",1)->first();

/**
* Join a table with a simple step
*/
$result = FooBar::table()->withTable("related_table")->first();

/**
* Auto select all from a table, and make them prefix with its table name
*/
$result = FooBar::table()
->join("related_table","related_table.id","=","related_table_id")
->addSelect("foo_bar.*")
->addSelectTable("related_table") // This will produce: related_table_id, related_table_created_at, etc
->first();

/**
* Add like condition to the query
*/
$result = FooBar::table()->like("column",$yourKeyword)->get();
// It will produce same as FooBar::table()->where("columne","like","%".$yourKeyword."%")->get()

/**
* Find a record by a specific condition
*/
$result = Foobar::findBy($column, $value = null);
// or 
$result = Foobar::findBy(['foo'=>1,'bar'=>2]);

/**
* To run the insert SQL Query
*/
$fooBar = new FooBar();
$fooBar->name = "Lorem ipsum";
$fooBar->save();

/**
* To bulk insert
*/
$data = [];
$foo = new FooBar();
$foo->name = "Lorem ipsum 1";
array_push($data, $foo);
$bar = new FooBar();
$bar->name = "Lorem ipsum 2";
array_push($data, $bar);
FooBar::bulkInsert($data);


/**
* To run the update SQL Query
*/
$fooBar = FooBar::findById($value);
$fooBar->name = "Lorem ipsum";
$fooBar->save();

/**
* To delete the record by a primary key value
*/
FooBar::deleteById($value);

/**
* To delete the record by a specific condition
*/
FooBar::deleteBy($column, $value = null);
// or
Foobar::deleteBy(['foo'=>1,'bar'=>2]);

/**
* To delete after you fetch the record 
*/
$fooBar = FooBar::findById($value);
$fooBar->delete();

一对一关系

class Posts extends Model {
    // etc
    
    /**
    * @return Illuminate\Support\Collection
    */
    public function comments() {
        return $this->hasMany(Comments::class);
    }
    
    // or with full option
    /**
    * @return Illuminate\Support\Collection
    */
    public function comments() {
        return $this->hasMany(Comments::class, "foreign_key", "local_key", function($condition) {
            return $condition->where("status","Active");
        });
    }
}

一对多关系

class Comments extends Model {
    // etc
    
    /**
    * @return App\Models\Posts
    */
    public function post() {
        return $this->belongsTo(Posts::class);
    }
    
    // or with full option
    /**
    * @return App\Models\Posts
    */
    public function post() {
        return $this->belongsTo(Posts::class, "foreign_key", "local_key");
    }
}

其他有用

  1. CRUDBooster Laravel CRUD生成器