所以我有一个表pages
,如下所示:
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->integer('category')->unsigned();
] });
Schema::table('pages', function($table) {
$table->foreign('user_id')->references('id')->on('core_users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('category')->references('id')->on('ecommerce_payment_pages_categories')
->onUpdate('cascade')->onDelete('set null');
});
}
public function down()
{
Schema::drop('pages');
}
表格类别
如下所示:
public function up()
{
Schema::create('ecommerce_payment_pages_categories', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('core_users')
->onUpdate('cascade')->onDelete('cascade');
$table->string('name');
$table->timestamps();
});
}
public function down()
{
Schema::drop('categories');
}
页面模型
如下所示:
class Pages extends Model
{
protected $table = 'pages';
public function user() {
return $this->belongsTo("\App\User");
}
protected $fillable = [
];
protected $casts = [
];
public function categories() {
return $this->belongsTo("\App\Models\Categories");
}
}
类别模型
如下所示:
class PaymentPagesCategories extends Model
{
protected $table = 'categories';
public function user() {
return $this->belongsTo("\App\User");
}
protected $fillable = [
];
protected $casts = [
];
public function pages_categories() {
return $this->hasMany("\App\Models\\Pages");
}
}
因此,在我的页面表中,我将用户从动态选择中选择的类别 ID 保存在列类别
中,该动态选择将类别 ID 作为值,将类别名称作为选项。但我无法将其保存为简单的字符串,因为在另一个菜单中用户可以选择删除类别,所以我希望当类别被删除时也从页表的类别列中删除。现在我显示数据库中的数据,如下所示:
public function getGet()
{
return response()->json(['success' => true, 'payment_pages' => \Auth::user()->payment_pages()->orderBy('id', 'ASC')->get()]);
}
因此,对于当前经过身份验证的用户,我显示页面数据库表中的所有数据。 现在,当用户从我的选择中选择一个类别后,我将类别的 ID 保存在页面表的类别列中。我需要进行查询,以便在 html 中的不同 View 中显示与我保存在页面表中的类别 id 相对应的内容
最佳答案
页面迁移中的类别列未设置为允许空值。 要允许空值,请将可为空的列修饰符附加到类别列。 其余代码看起来没问题。
页面迁移:
public function up()
{
Schema::create('pages', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('name');
$table->integer('category')->unsigned()->nullable(); // <= add this modifier
});
Schema::table('pages', function($table) {
$table->foreign('user_id')->references('id')->on('core_users')
->onUpdate('cascade')->onDelete('cascade');
$table->foreign('category')->references('id')->on('ecommerce_payment_pages_categories')
->onUpdate('cascade')->onDelete('set null');
});
}
关于php - Laravel 使用该行的 id 显示一个数据库表中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40405541/