Php 拉维关系设计
我在做团队管理项目。 我在处理人际关系方面有问题 我想在黑板上显示用户,但也希望看起来很好,易于阅读。我已经设计了关系,但当我看到关系的JSON输出时,它完全混乱了 有什么方法可以这样显示关系数据吗Php 拉维关系设计,php,laravel,eloquent,relationship,Php,Laravel,Eloquent,Relationship,我在做团队管理项目。 我在处理人际关系方面有问题 我想在黑板上显示用户,但也希望看起来很好,易于阅读。我已经设计了关系,但当我看到关系的JSON输出时,它完全混乱了 有什么方法可以这样显示关系数据吗 { "id": 1, "name: "Test", "members": [ { ... user model here "name": "Peter", "email": "peter@
{
"id": 1,
"name: "Test",
"members": [
{
... user model here
"name": "Peter",
"email": "peter@peter.com",
}
]
}
我的迁移:
电路板迁移
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBoardsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('boards', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('boards');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMembershipsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('memberships', function (Blueprint $table) {
$table->increments('id');
$table->integer('board_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('memberships');
}
您可以尝试将模型中的关系定义为多对多关系,即:
class User
{
public function boards()
{
return $this->belongsToMany('App\Board', 'memberships', 'user_id', 'board_id');
}
}
class Board
{
public function members()
{
return $this->belongsToMany('App\User', 'memberships', 'board_id', 'user_id');
}
}
定义了这些关系后,如果成员模型没有其他字段,则实际上不需要成员模型,您可以编写如下代码:
User::find($id)->boards
Board::find($id)->members
Board::with('members')->find($id)
您也可以阅读上的文档,告诉我们您在哪里设置关系,即belongsTo
、hasOne
、hasMany
等。您的问题是什么?你是说有董事会的成员吗<代码>Board::with('members')->get()
?这不是我想要的,我得到的JSON看起来像这样,JSON是App\Board::with('members')->get()的结果代码>?否,$board->成员的JSON结果代码>请尝试App\Board::with('members')->get()代码>或App\Board::with('members')->find($id)代码>我想这看起来像是你们关系的结果,而不是我发布的那些
User::find($id)->boards
Board::find($id)->members
Board::with('members')->find($id)