gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:55:18 24 4
gpt4 key购买 nike

我有两个表 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');
}
}

希望这对你有用!!!

关于php - 为数据库中的两个新表创建模型和关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45462874/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com