2017-05-07 313 views
0

因此,让我们假设我们有基于我们的表(Post和标签)Laravel:一对多,许多对一个模型一对多关系

岗位有(一对多)的关系有这样两个Model称为高亮标记字段,它只接受一个标记。

该帖子还有一个(多对多)关系将标签分配到该帖子,所以它就像普通标签。

据我所知,你不能有多个关系分配给同一个表,这怎么可能使用Laravel?最佳做法是什么?

回答

0
You can do following : 

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Post extends Model 
{ 

    public function tags(){ 

     return $this->hasMany('App\Tag'); 
    } 

    public function highlightedtag(){ 

     return $this->tags->where('tag_type', 'highlighted')->first(); 
    } 

} 

?> 

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Tag extends Model 
{ 

    public function posts(){ 

     return $this->hasMany('App\Post'); 
    } 

} 

?> 
+0

要让标签需要有多对多的关系,一对多根本不起作用,而在答案中,您没有考虑具有相同突出显示的标签的其他帖子。 – Mike

0

如果我正确理解你的意思,你希望这篇文章有一个主要(高亮标记)标记和多个普通标记。这很容易。

你的Post模型功能:

public function tag() 
{ 
    //Your highlighted tag 
    return $this->belongsTo(Tag::class); 
} 

public function tags() 
{ 
    //All normal tags 
    return $this->hasMany(Tag::class); 
} 

而这些都是你的表的列:

posts表:

id: int 
title: string 
content: string 
tag_id: int 

tags表:

id: int 
name: string 
post_id: int 
+0

不幸的是,这不起作用,我们需要多对多的关系才能让标签摆在首位。一对多不起作用。 同样在答案中,我们短1数据库字段,我们在哪里放置突出显示的标记ID!? – Mike