php - 如何在redbeanphp中创建具有自定义名称的外键

标签 php mysql redbean

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

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

我使用这个代码:

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

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

我该怎么做?有没有办法在 redbeanphp 框架中创建具有最喜欢名称的自定义外键?

最佳答案

通过您的示例,您可以使用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
*/

关于php - 如何在redbeanphp中创建具有自定义名称的外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30951705/

相关文章:

php - WAMP .htaccess 在从 XAMPP 移动后出现内部服务器错误

mysql - 新的 MySQL 服务器比旧的慢

php - RedBeanPHP 没有正确保存字符串,从带重音的元音开始跳过

php - foreach 在 while 循环中获取行值...?

javascript - PHP 到 JSON 数组输出错误

php - Woocommerce 中我的帐户订单列表上的条件取消按钮

php - 在redbean php中获取 'owner' bean

mysql - 按列索引而不是按列名更新表

mysql - 如何获取表格中满足不同条件的产品和价格列表

php - RedBean ORM 性能