486   Laravel PHP

laravel5 文章post与分类category的关联,属于一对多或者说多对一的关联,跟文章post与用户users关联一样

首先,posts表中创建category_id的字段,同时在Posts模型中添加函数category()

namespace App;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model
{
    //
	protected $table = 'posts';

    protected $fillable = ['title', 'content', 'active', 'user_id','category_id'];

	public function user() 
	{
		return $this->belongsTo('App\User');
	}

	public function category() 
	{
		return $this->belongsTo('App\Categories');
	}
}

然后,新建categories表格和模型,在模型中添加函数posts()

namespace App;

use Illuminate\Database\Eloquent\Model;

class Categories extends Model
{
    //
    protected $table = 'categories';

    protected $fillable = ['name'];

    public $timestamps = false;

    public function posts() 
    {
      return $this->hasMany('App\Posts','category_id');
    }
}

设置完毕之后,就可以在post类中找到category了


$post = Posts::findOrFail($id);
$category = $post->category;

同时也可以找到category所有的posts

        $category = Categories::findOrFail($id);
        $page_title = $category->name;
        $posts = $category->posts()
            ->orderBy('updated_at', 'desc') // 排序
            ->paginate($this->per_page);//分页




Leave a Reply

Your email address will not be published. Required fields are marked *