Laravel的ORM入門

源碼目錄在\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Relations下php

關係:一對多(One To Many)laravel

場景:每篇博客都有若干條評論,每條評論只屬於一篇博客post

先定義兩個Model,這裏爲了突出主要矛盾,刪除了Model中部分無關代碼this

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的模型spa

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');
        }
}

控制器裏:blog

$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;
        }
}
相關文章
相關標籤/搜索