// both main and related object already exist
$user = Model_User::find(8);
$user->posts[1] = Model_Post::find(1);
$user->save();
Model_User::find(2)->books[2] = Model_Book::find(2)
$user = Model_User::find(2);
echo $user->id; //will bring out user id;
//to access books user has
$books=$user->books; //will give you a handle on the books
i hope this was helpful
$user->posts[1] = Model_Post::find(1);
$user->posts[] = Model_Post::find(1);assuming the relation from users to posts is called 'posts'. So this line says "Assign the result of the find operation to the many relation between users and posts.
$user->posts = Model_Post::find(1);so without the array brackets.
public function action_subscribe($book_id) {
if (Auth::check()) {
$user = Model_User::find(Auth::get('id'));
$book = Model_Book::find($book_id);
$user->books[] = Model_Book::find($book_id);
if ($user and $user->save()) {
Session::set_flash('success', e('Added book #' . $book->id . ' to your subscriptions.'));
}
else {
Session::set_flash('error', e('Could not add book to your subscriptions'));
}
}
else {
Response::redirect('member/login');
}
}
protected static $_many_many = array(
'users' => array(
'key_from' => 'id',
'key_through_from' => 'book_id', // column 1 from the table in between, should match a books.id
'table_through' => 'books_users', // both models plural without prefix in alphabetical order
'key_through_to' => 'user_id', // column 2 from the table in between, should match a users.id
'model_to' => 'Model_User',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => false,
)
);
protected static $_many_many = array(
'books' => array(
'key_from' => 'id',
'key_through_from' => 'book_id', // column 1 from the table in between, should match a books.id
'table_through' => 'books_users', // both models plural without prefix in alphabetical order
'key_through_to' => 'user_id', // column 2 from the table in between, should match a users.id
'model_to' => 'Model_Book',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => false,
)
);
It looks like you're new here. If you want to get involved, click one of these buttons!