Eloquent ORM
Laravel 的 Eloquent ORM 提供了漂亮、简洁的 ActiveRecord 实现来和数据库交互。每个数据库表都有一个对应的「模型」用来与该表交互。你可以通过模型查询数据表中的数据,并将新记录添加到数据表中。
定义模型
php artisan make:model User
例子
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Flight extends Model
{
/**
* 与模型关联的数据表
*
* @var string
*/
protected $table = 'my_flights';
}
定义关联(一对多)
/**
* 获得此博客文章的评论。
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
定义反向关联
/**
* 获得此评论所属的文章。
*/
public function post()
{
return $this->belongsTo('App\Post', '外键');
}
例子
获得所有至少有一条评论内容满足 foo% 条件的文章
Post::whereHas('comments', function ($query) {
$query->where('content', 'like', 'foo%');
})->get();