Fuelphp Like logic with orm
-
04-07-2021 - |
Question
I have a small site where I would like to give the ability to users to like each profile with ajax.
So the logic is this, if the use clicks on the like it inserts, but if the person already liked and that's found in the database delete the record this would be the unlike function.
So the controller looks like this.
public function action_like()
{
$response = Response::forge();
$like = Model_Like::forge();
$like->user_id = Input::post('user_id');
$like->liked_by = Session::get('sentry_user');
// find if the user already liked
$row = Model_Like::find(array($like->user_id, $like->liked_by));
//if liked remove from database
if($row):
$response->body(json_encode(array(
'status' => 'no',
)));
$row->delete();
else:
$response->body(json_encode(array(
'status' => 'yes',
)));
$like->save();
endif;
return $response;
}
javascript
$('button.like').on('click', function(){
var likeId = $(this).data('like')
valPlus = parseInt($('.like-total').text()) + 1;;
$.ajax({
type: "POST",
url: site_url + 'profile/like/',
data: {user_id: likeId},
dataType: "json",
context: this,
//async: false,
beforeSend: function(data) {
$(this).attr('disabled', 'disabled');
},
success: function(data) {
console.debug(data);
if(data.status == "yes") {
$('.like-total').text(valPlus);
}
},
complete: function(data) {
$(this).removeAttr('disabled', 'disabled');
}
})
});
So the problem is that the $row
always retunrs null
, so it is not locating the two id's and always inserts.
Could please someone give me a hint what I am missing?
Solution
I think you have an error in your "Where". Can you try with this?
$row = Model_Like::find()->where(array(
array('user_id', $like->user_id),
array('liked_id', $like->liked_by)
));
With your "Where" you where searching for the records with ids "$like->user_id" and "$like->liked_by", not for a single row with both of them.
OTHER TIPS
Seen a similar question today on here.
You can do
Model_Like::find_by_user_id_and_liked_id($like->user_id, $like->liked_by);
As per the documentation: find() requires a primary key as parameter.
You can run a query by using the solutions mentioned by "Marco Pace" and "notrab". In the first case, use
Model_Like::query()
and not
Model_Like::find()
The last one just happens to work because not passing any parameters is an error situation in which the ORM's query object is returned because it doesn't know what to find. This behaviour might change in future versions.