2017-05-07 324 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