I has two table Post(id, text, id_tag) and Tag(id, name). How create relationship for two this table and how create models for work framework with this table.
You should create two model 1) Tag 2) Post like:
1) Tag
<?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) Post
<?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');
}
}
Hope this work for you !!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.