【发布时间】:2016-06-02 23:09:02
【问题描述】:
我有 3 个表用户、个人资料和朋友。
显然,Users 包含用户。 然后我得到了 Profiles and Friends 表(见下文)。
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->string('picture')->nullable();
$table->string('status')->nullable();
$table->string('text')->nullable();
$table->boolean('show_sex');
$table->boolean('show_dob');
$table->timestamps();
});
}
public function up()
{
Schema::create('friends', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id_sender')->unsigned();
$table->integer('user_id_receiver')->unsigned();
$table->foreign('user_id_sender')->references('id')->on('users');
$table->foreign('user_id_receiver')->references('id')->on('users');
$table->integer('status'); // 1 = friends, 2 = under validation
$table->timestamps();
});
}
如您所见,我创建了一些与 Users 表相关的外键。
Friends 表包含用户之间的所有友谊(状态字段将确定友谊是正在验证中还是已验证)。
我有 Laravel 5.2 附带的默认用户模型,我想知道如何轻松获得属于已签名用户的所有友谊?
我可以使用 belongsTo() 之类的东西或其他东西来轻松获取 user_id_receiver 字段与签名用户 ID 相同的所有朋友请求吗?我不太了解 hasOne 或 belongsTo. 的文档。如果有人能阐明它的实际工作原理,那就太好了。
提前致谢。
【问题讨论】:
-
我最好的建议是在你直接去编码和询问 Laravel 之前,尝试设计你的数据库表(ER-design),当你知道它会让你的代码逻辑更容易时。
标签: php eloquent laravel-5.2