2017-08-02 102 views
1

我有兩個表Post(id,text,id_tag)和Tag(id,name)。 如何爲兩個表創建關係,以及如何使用此表爲工作框架創建模型。在DB中創建模型和兩個新表的關係

+0

對於Model'php artisan make:model ModelName'在命令中使用 AND轉到https://laravel.com/docs/5.4/queries#joins –

回答

0

你應該建立兩個模型1)標籤2)後,如:

1)標籤

<?php 

namespace App\Models\frontend; 

use Illuminate\Database\Eloquent\SoftDeletes; 
use Illuminate\Database\Eloquent\Model; 

class Tag extends Model 
{ 
    use SoftDeletes; //<--- use the softdelete traits 

    protected $dates = ['deleted_at']; //<--- new field to be added in your table 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'tag'; 

    /** 
    * The database primary key value. 
    * 
    * @var string 
    */ 
    protected $guarded = ['id', '_token']; 

    /** 
    * Attributes that should be mass-assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = ['name']; 



    /** 
    * That belong to the Tag. 
    */ 
    public function post() 
    { 
    return $this->hasMany('App\Models\Post'); 
    } 
} 

2)郵政

<?php 

namespace App\Models; 

use Illuminate\Database\Eloquent\SoftDeletes; 
use Illuminate\Database\Eloquent\Model; 

class Post extends Model 
{ 
    use SoftDeletes; //<--- use the softdelete traits 

    protected $dates = ['deleted_at']; //<--- new field to be added in your table 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'post'; 

    /** 
    * The database primary key value. 
    * 
    * @var string 
    */ 
    protected $guarded = ['id', '_token']; 

    /** 
    * Attributes that should be mass-assignable. 
    * 
    * @var array 
    */ 
    protected $fillable = ['text','id_tag']; 

    /** 
    * The roles that belong to the Post. 
    */ 
    public function tag() 
    { 
    return $this->belongsTo('App\Models\Tag','id_tag'); 
    } 
} 

希望這對你的工作!

相關問題