在DB中为两个新表创建模型和关系

时间:2017-08-02 13:53:25

标签: php mysql database laravel laravel-5.3

我有两个表Post(id,text,id_tag)和Tag(id,name)。 如何为此表创建关系以及如何使用此表为工作框架创建模型。

1 个答案:

答案 0 :(得分: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');
  }
}

希望这对你有用!!!