如何在redbeanphp中创建一个自定义名称的外键

how to create a foreign key with custom name in redbeanphp

我有两个 table usercomment:一个用户可以 post 对另一个用户发表评论。

我想创建两个从 comment table 到 user table 的外键,一个包含评论作者 user_id,另一个包含评论所有者 user_id.

我使用这个代码:

$agent->link($TB_Comment,array("comment"=>$comment, "indate"=>  time()))->sharedUsers = $user ;

它会在我的 table (user_id , sharedUser_Id) 中创建此列 但我想将 sharedUser_Id 重命名为 writerId ...

我该怎么做?有没有一种方法可以在 redbeanphp 框架中使用最喜欢的名称创建自定义外键?

我在关于页面 的 readbean 中发现我的问题的答案绝对是 不是 。 在 this 页的最后一节写了这一段:

You should also NOT use RedBeanPHP if you don't like the RedBeanPHP schema policies and you want complete control over the layout of your database schema, i.e. the column names used for primary keys and foreign keys. In this case I recommend to use: Doctrine. If Doctrine is too big for your taste you might also consider a small, active record like ORM written by a friend of mine: DicaORM.

根据您的示例,您可以使用 aliases.

轻松实现非常接近(writer_id,而不是 writerId)的目标

查看此片段:

<?php

require 'rb.php'; // rb 4.2.4 (for the record)

R::setup();

list($owner, $writer) = R::dispenseAll('user*2')[0];

$owner->name = 'Owner';
$writer->name = 'Writer';

R::storeAll([$owner, $writer]);

$comment = R::dispense('comment');
$comment->user = $owner;
$comment->writer = $writer;

$commentId = R::store($comment);

// Schema with user_id & writer_id:
print_r(R::load('comment', $commentId)->export());
/*
Array
(
    [id] => 4
    [user_id] => 7
    [writer_id] => 8
)
*/

// This fails:
$comment = R::load('comment', $commentId);
echo $comment->writer->name . ' => ' . $comment->user->name . "\n";
/*
 => Owner
*/

// But, using aliases, this works:
$comment = R::load('comment', $commentId);
echo $comment->fetchAs('user')->writer->name . ' => ' . $comment->user->name . "\n";
/*
Writer => Owner
*/

// Or, using aliases & magic:
R::setAutoResolve(true); // magic!
$comment = R::load('comment', $commentId);
echo $comment->writer->name . ' => ' . $comment->user->name . "\n";
/*
Writer => Owner
*/