laravel学习(四)-----模型&Eloquent ORM学习

通过Facade\DB使用sql原生查询比较麻烦,并且每个功能类中都需要实现一次SQL语句编写,通过Eloquent ORM 在model中创建一个表的sql操作,只需要在model中实现一次,其他功能类就可以直接调用,并且Laravel在model层的一些build query函数都很多很全,展示了它的强大之处

贴上官方laravel6.x文档链接
本博文概要:
1. 数据库生成
2. laravel中model操作
3. controller中关于Eloquent的增删改查命令

6.x版本的laravel移除了默认model目录,支持用户自己定义一个model目录
也可以通过laravel 的artisan来自动部署model内容

一、数据库生成

php artisan make:model Article

也可以在创建model同时生成一个数据库的迁移

php artisan make:model Flight --migration

php artisan make:model Flight -m

手写或者artisan生成内容:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    //
}

通过命令生成迁移文件后还需要修改迁移文件设置列属性

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateArticlesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Articles', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('content')->comment('文章信息');
            $table->text('author')->comment('文章作者');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('articles');
    }
}

修改好迁移文件之后,还需要用命令来生成mysql表,因为此时mysql中还未有对应表生成,指定database在.env文件中
在这里插入图片描述
在这里,我们需要.env连接库和mysql中库名一致,迁移文件修改好
然后我们用命令:

php artisan migrate

在这里插入图片描述
在这里插入图片描述
期间如果遇到下面问题:
在这里插入图片描述
我们尝试将app\Providers\AppServiceProvider.php修改如下即可:

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Schema::defaultStringLength(191);
    }
}

二、laravel中model操作

  • 我们需要在建立之后设置连接数据表名 以及主键约定
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * 与模型关联的表名
     *
     * @var string
     */
    protected $table = 'my_flights';
    /**
     * 重定义主键
     *
     * @var string
     */
    protected $primaryKey = 'flight_id';
    /**
     * 指示模型主键是否递增
     *
     * @var bool
     */
    public $incrementing = false;
    /*如果你的主键不是一个整数,你需要将模型上受保护的 $keyType 属性设置为 string*/
    /**
     * 自动递增ID的“类型”。
     *
     * @var string
     */
    protected $keyType = 'string';
    
}

三、Eloquent ORM

到这里 我们表创建好了,model在刚才第一行命令时也已经创建好,现在学习关于基于laravel的一些sql操作

生成一个blog\ArticleController

php artisan make:controller Blog/ArticleController
  1. 单条插入
    public function index()
    {
    	$bool = \App\Article::insert(
    		['content'=>'这是插入的第一条数据',
    		 'author' =>'我的名字叫张三'
    		]
    	);
    	return $bool ? 'success' : 'failed';
    }

在这里插入图片描述
在这里插入图片描述

  1. 单条插入
    public function index()
    {
    //只需要将上面的一维数组该为二维数组即可
    	$bool = \App\Article::insert(
    		[['content'=>'这是插入的第二条数据','author' =>'我的名字叫李二'],
    		 ['content'=>'这是插入的第三条数据','author' =>'我的名字叫张三']

    		]
    	);
    	return $bool ? 'success' : 'failed';
    }

在这里插入图片描述

  1. 获取插入的id值
    public function index()
    {
    	//这里不能进行批量插入
    	//如果想获取非id列的默认自增字段 ,需要在第二个参数声明列名
    	$id = \App\Article::insertGetId(
    		['content'=>'这是插入的第二条数据','author' =>'我的名字叫李二']
    
    	);
    	return $id;
    }

在这里插入图片描述

	public function index()
    {
    	//删除Article中所有信息(谨慎)
    	$countDelete = \App\Article::delete();
    	//条件删除
    	$countDelete = \App\Article::where('id', '>', 3)->delete();

    	//取回模型再删除
    	//生产环境下一般设置软删除 而不是直接删除记录
    	$articles = \App\Article::find(1);
    	$articles->delete();

    	\App\Article::destroy(1);
    	//批量删除
    	\App\Article::destroy([1,2,3]);
    		
    }

生成环境中我们一般使用软删除,防止数据永久丢失
步骤:1.现在表中没有deleted_at字段,需要修改迁移

    public function up()
    {
        //
        Schema::table('Articles', function (Blueprint $table) {
            $table->softDeletes();
        });
    }

步骤 2.Model引入SoftDeletes;

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
    //
    use SoftDeletes;
    protected $dates = ['delete_at'];
}

如下进行删除

    public function index()
    {
        $article  = \App\Article::find(12);
        $article->delete();
        if ($article->trashed()){
            return '已删除';
        }
        return '未删除';
    }

在这里插入图片描述
关于软删除 还有一些其他操作 比如查

 //查询数据  包含 存在+已删除(软删除) 的数据
 $article  = \App\Article::withTrashed()
                         ->where('id',12)
                         ->get();
 //查询数据  只获取软删除数据
 $article = \App\Article::onlyTrashed()
                         ->get(); 
 //还原软删除数据
 $article  = \App\Article::withTrashed()
                         ->restore();     

 //在开启软删除中彻底删除数据
 $article->forceDelete();                    
 return $article; 
    public function index()
    {
    	$bool = \App\Article::where('id',7)->update(['content'=>'这是我修改的第一条数据']);
    	return $bool;
    }

在这里插入图片描述
通过模型Model的find和save我们也可以进行更新

    public function index()
    {
    	//获取主键对应行 进行更新
    	$article = \App\Article::find(7);
    	$article->content = '这是我修改的第二条数据';
    	$article->save();
    }
  1. 获取所有行信息
	public function index()
	{
		//获取当前所有行
		$articles = \App\Article::all();
		return $articles;
	}

在这里插入图片描述

  1. 获取条件查找的第一条行信息
	public function index()
	{
		//获取当前行的第一条数据
		$articles = \App\Article::where('author','我的名字叫张三')->first();
		return $articles;
	}

在这里插入图片描述

  1. 返回行数据的某列数据
	public function index()
	{
		//返回行的某列数据
		$articles = \App\Article::where('id','>','2')->value('content');
		// select `content` 
		//         from `articles` 
		//         where `id` > 2 
		//         limit 1;

		//符合条件筛选的某列信息集合
		$articles = \App\Article::where('id','>','2')->pluck('content');

		//返回 id:content对应的信息  pluck最多两条数据
		$articles = \App\Article::where('id','>','2')->pluck('content','id');
		return $articles;
	}

在这里插入图片描述

  1. 其他聚合类型
	public function index()
	{
		$count = \App\Article::count();
		$max = \App\Article::max('id');
		$min = \App\Article::min('id');
		$avgId = \App\Article::avg('id');
		$sum = \App\Article::sum('id');

		print("count->$count  max->$max min->$min  avgId->avgId  sum->$sum");
	}

在这里插入图片描述

  1. 高级子查询&&where使用
        $article = \App\Article::where('id', 8)->get(); // 简单查找
        $article = \App\Article::where('id', '<>', 8)->get();//范围查找
        $article = \App\Article::where('author', 'like', '%李二%')->get();//模糊查找
        $article = \App\Article::where([
                                        ['id', '>', 8],
                                        ['author','like', '%李二%']
                                    ])->get();  //多条件查找
        
        $article = \App\Article::whereBetween('id', [3,10])->get(); //范围查找 3~10
        $article = \App\Article::whereNotBetween('id', [3,10])->get(); // 范围外查找
        
        $article = \App\Article::whereIn('id', [1,2,3,4,5])->get(); // 数组查找
        $article = \App\Article::whereNotIn('id', [1,3,2,4])->get(); // 数组外查找

        $article = \App\Article::whereNull('created_at')->get(); // 空列查找
        $article = \App\Article::whereNotNull('created_at')->get(); // 非空列查找

        $article = \App\Article::whereDate('updated_at', '2020-3-26')->get(); // 日期查找
        $article = \App\Article::whereMonth('created_at', '12')->get(); // 月份查找
        $article = \App\Article::whereDay('created_at', '31')->get(); // 日查找
        $article = \App\Article::whereYear('created_at', '1')->get(); // 年查找
        $article = \App\Article::whereTime('created_at', '>','31')->get(); // 时分秒查找

        $article = \App\Article::whereColumn('updated_at', 'created_at')->get(); // 两个字段相等查找
        $article = \App\Article::whereColumn('updated_at', '>', 'created_at')->get(); // 两个字段不等查找
        $article = \App\Article::whereColumn([
                                                ['updated_at', '>', 'created_at'],
                                                ['id', '>', 'author']
                                            ])->get(); // 两个字段过滤查找

        //join
        $article = \App\Article::join('table2', 'articles.id','=','table2.article_id')
                                ->select('articles.*', 'table2.id')
                                ->where('articles.id','=', 2)
                                ->get(''); // 连接查找
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值