text Laravel Eloquent数据库示例(5.6)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text Laravel Eloquent数据库示例(5.6)相关的知识,希望对你有一定的参考价值。

```php
<?php

/**
 * MySQL Functions in Laravel 5.6 using ELOQUENT
 *
 * @see    : https://laravel.com/docs/5.6/eloquent
 * @Author : Kit
 * @Role   : LARAVEL NEWBIE / bored PHP bedroom hacker
 * @Written: Around May 2018
 *
 * @Note   : Still trying to understand the purpose of wrapping this into high level when everyone already knows SQL syntax ??
 *
 * NOTE: you MUST use mysql 5.7 to use the `json` field type!
 * You canNOT upgrade an Aurora instance to 5.7 - must dump, create new and insert
 */

/*
* |--------------------------------------------------------------------------
* | MODELS - make life easier
* |--------------------------------------------------------------------------
*/
// php artisan make:model TABLE -m
// this also creates a migration (app/database/migrations)
// model in (app/xxx.php)

/*
* |--------------------------------------------------------------------------
* | Example migration - we can do this in either the migrations folder or do it anywhere in real time
* |--------------------------------------------------------------------------
*/
Schema::create('github_gists', function (Blueprint $table) {
	$table->increments('id');
	$table->int('timestamp')->default(strtotime('now')); // ADD DEFAULT UNIX TIMESTAMP
	$table->string('gist_id')->unique()->nullable(); // UNIQUE, ALLOW NULL
	$table->string('language')->unique()->nullable(); // UNIQUE, ALLOW NULL
	$table->json('json')->nullable(); // ALLOW NULL - create a JSON type field, new in mysql 5.7
	$table->timestamps(); // this makes created_at and updated_at fields
	$table->index(['gist_id', 'created_at']); // ADD AN INDEX ON THESE COLUMNS
});
/*
|--------------------------------------------------------------------------
| SELECT examples
| @see: https://laravel.com/docs/5.6/queries
|--------------------------------------------------------------------------
*/
$value = DB::table('github_gists')->where('id', 1)->orderBy('id', 'desc')->take(1)->get();
$value = DB::table('github_gists')->where('id', '>', 1)->orderBy('id', 'desc')->take(10)->get();
$value = DB::table('github_gists')->where('id', '=', 1)->get();
$value = DB::table('github_gists')->where('id', '=', 1)->orWhere('timestamp', '<', strtotime('now')); // nb - kludge / hack

// fetch random
$input = \DB::table('wordnet.samples')
    ->select('sample')
    ->inRandomOrder()
    ->first();

// fetch from a JSON row directly without having to parse the object/array - cool
$value = DB::table('github_gists')->where('results->language', 'Markdown')->get();

$value = DB::table('users')->where('name', 'John')->first();
$value = DB::table('users')->where('name', 'John')->value('email');

// get count of rows in table
$value = DB::table('users')->count();

// select values
$value = DB::table('users')->select('name', 'kit')->get(); 

// get count of distinct per field, e.g. ip
$value = DB::table('users')->distinct('ip')->count('ip');

$value = DB::table('orders')->max('price');
$value = DB::table('orders')->min('price');
$value = DB::table('orders')->sum('price');
$value = DB::table('orders')->avg('price');

// more complex example

$output = \DB::table('translations_from_api')
    ->select(
        'input',
        'output',
        'api_weight',
        'provider_slug'
    )
    ->where('provider_slug', '=', $provider_slug)
    ->where('input', '=', $input)
    ->where('timestamp', '>', $recent)
    ->orderBy('timestamp', 'asc') // most recent only
    ->take(1)

// output as JSON
// TODO, there is a wrapper, but can't figure it out yet
$value = DB::table('github_gists')->where('id', 1)->select('json')->get();;
$output = json_encode($value, JSON_PRETTY_PRINT);
//$output = $value->(JSON_PRETTY_PRINT);

// RAW STATEMENTS
$value = DB::table('users')->select(DB::raw('count(*) as user_count, status'))->where('status', '<>', 1)->groupBy('status')->get();

// RAW WITH PDO (inject proof)
$value = DB::table('orders')->selectRaw('price * ? as price_with_tax', [1.0825])->get();

/*
|--------------------------------------------------------------------------
| INSERT examples
|--------------------------------------------------------------------------
*/
DB::table('github_gists')->insert([['gist_id' => $filename, 'json' => $json]]);

/*
|--------------------------------------------------------------------------
| TRUNCATE examples
|--------------------------------------------------------------------------
*/
DB::table('github_gists')->truncate();

/*
|--------------------------------------------------------------------------
| UPDATE examples
|--------------------------------------------------------------------------
*/
DB::table('github_gists')->where('id', 1)->where('gist_id', 'xxxx')->update(['json' => $json]);

/*
|--------------------------------------------------------------------------
| Enable query log and output
|--------------------------------------------------------------------------
*/
DB::connection()->enableQueryLog();
// .... then execute queries ... //
$queries = DB::getQueryLog();
print_r($queries);

/*
|--------------------------------------------------------------------------
| Eloquent has no REPLACE, therefore we must do a DELETE if exists (using a select) then an insert
| You could use: https://github.com/jdavidbakr/replaceable-model - but why?
| Speed note: AFAIK MySQL REPLACE is simply a DELETE followed by an INSERT anyway
|--------------------------------------------------------------------------
*/
DB::table('github_gists')->where('gist_id', $filename)->delete();
DB::table('github_gists')->insert([['gist_id' => "$filename", 'json' => $json]]);

/*
 * OR, we can do it with good old SQL - PDO style
*/
DB::insert('replace into github_gists (gist_id, json) values (?, ?)', [$filename, $json]);


/*
|--------------------------------------------------------------------------
| TRANSACTIONS
|--------------------------------------------------------------------------
*/
// TODO - probably not needed unless writing an ecommerce platform or bank or something where the transaction absolutely cannot fail

/*
|--------------------------------------------------------------------------
| Create a schema based on JSON OUTPUT to effectively dump any API output into MySql
|--------------------------------------------------------------------------
*/

//TODO

// probably : https://laravel.com/docs/5.6/eloquent-mutators
```

以上是关于text Laravel Eloquent数据库示例(5.6)的主要内容,如果未能解决你的问题,请参考以下文章

Laravel 5.1用eloquent删除DB中的重复项

Laravel Eloquent - 从相关模型中检索特定列

Laravel:Eloquent模型中的多重多态关系

Laravel Eloquent:如果搜索文本字段为空,如何显示所有行

PHP Laravel 在所有视图中使用辅助类

Laravel教程 四:数据库和Eloquent