how to create a foreign key with custom name in redbeanphp

643 views Asked by At

I have two tables user and comment: a user can post a comment to another user.

I want create two foreign key from comment table to user table witch one contain comment writer user_id and another contain comment owner user_id.

i use this code :

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

and it create this column in my table (user_id , sharedUser_Id) but i want to rename sharedUser_Id to writerId ...

how can i do this? and is there a way to create custom forign key with favorite name in redbeanphp framework ?

2

There are 2 answers

0
rixo On BEST ANSWER

With your example, you can achieve something very close (writer_id, instead of writerId) to what you want easily using aliases.

See this snippet:

<?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
*/
2
Navid_pdp11 On

i found answer of my question in readbean about page witch was absolutely Not. in last section of this page this paragraph was written:

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.