Laravel的ORM入门
2024-10-19 02:26:03
源码目录在\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations下
关系:一对多(One To Many)
场景:每篇博客都有若干条评论,每条评论只属于一篇博客
先定义两个Model,这里为了突出主要矛盾,删除了Model中部分无关代码
namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model
{
protected $table = 'posts';
public function Comments()
{
return $this->hasMany('App\Comment','PostID','CommentID');
}
}
以上是博客Post的模型,接下来是评论Comment的模型
namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model
{
protected $table = 'comments';
public function Comment()
{
//
} public function Post()
{
return $this->belongsTo('App\Post','CommentID','PostID');
}
}
控制器里:
$articles=Post::where('id','>','50')->where('id','<','52')->get();
foreach($articles as $a){
//echo $a->id;
$comments=$a->Comments;
foreach($comments as $c){
//echo $c->id;
}
}
最新文章
- 原生js学习笔记2
- Matlab程序 转C++/Opencv基于Mat 不可不知的17个函数
- 记录创建企业Wiki的几个开源项目
- Summary: How to calculate PI? Based on Monte Carlo method
- IOS LocationManager定位国内偏移,火星坐标(GCJ-02)解决方法
- sharepoint rest api 创建文档库 文件夹
- 支持行单击、双击事件的GridView和DataList控件(译)
- hive的map类型处理
- tp3.2 上传文件及下载文件
- MT【292】任意存在求最值
- HDOJ 4267 A Simple Problem with Integers (线段树)
- input输入框只能输入数字而且开头不能为零
- [LeetCode] 504. Base 7_Easy tag: Math
- 学习笔记3—matlab中load特殊用法
- iOS.FBTweak
- 【转】Mysql学习---SQL的优化
- WebAPI 消息处理器
- Mac下Homebrew的图形化界面工具Cakebrew
- asp.net mvc access数据库操作
- linux top命令查看系统资源