繁体   English   中英

在数据库中为两个新表创建模型和关系

[英]Create models and relationship for two new tables in DB

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

您应该创建两个模型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');
  }
}

希望这项工作为您服务!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM