Eloquent: check extra pivot column - eloquent

Inside my User model I would like to make a isMember function.
public function isMember()
{
return(\Auth::check() && "get the status value here" == 1)
}
I got two models. User, Club.
Their pivot table: club_user
user_id
club_id
status
The 'status' column holds 0 or 1.
Now, how do i check the value for the extra column 'status'?
Update:
It's a many-to-many relationship.

Try This:
public function isMember(){
if(\Auth::check())
return (bool) $this->status;
return false;

Well, I got it to work. If somebody got some suggestions how to make it better, please fell free.
public function isMember($clubId)
{
$user = Club::find($clubId)->user()->where('club_user.user_id', \Auth::id())->first();
if (is_object($user))
{
$status = $user->pivot->status;
else
{
$status = 0;
}
return (\Auth::user() && $status == 1);
}

Related

What are the reordering columns on laravel-backpack?

In the official documentation, the following columns are mentioned :
parent_id
lft
rgt
depth
I haven't found any explanation of their types in the documentation. Could someone help me and tell me what they are ?
I also want to know if they are all mandatory if I only want to reorder a list of items (I don't need any nesting).
Edit: As this question is quite popular, I've updated the documentation with the correct info.
The reordering id columns should be integer or INT(10) if you're not using a migration.
Unfortunately they're all mandatory, yes. But if you're on a very strict DB schema, you could eliminate all of them except the "lft" column by adding this method to your EntityCrudController (basically overwriting the one in Backpack\CRUD\app\Http\Controllers\CrudFeatures\Reorder):
public function saveReorder()
{
$this->crud->hasAccessOrFail('reorder');
$all_entries = \Request::input('tree');
if (count($all_entries)) {
$count = 0;
foreach ($all_entries as $key => $entry) {
if ($entry['item_id'] != '' && $entry['item_id'] != null) {
$item = $this->crud->model->find($entry['item_id']);
$item->lft = empty($entry['left']) ? null : $entry['left'];
$item->save();
$count++;
}
}
} else {
return false;
}
return 'success for '.$count.' items';
}

Statistic Calculations in laravel

I'm working on a project for golfstatistics. Right now I made it so far to enter and edit golfstatistics. I'm working with laravel 5 btw.
My database schema works like this:
Every round you play saves one entry in the round table with information like (date, playid, weather, courseid)
for every hole played an entry in the score table is made. There I have a reference to the roundid and information like (score, fairwayhit, greenhit, putts, penalties, ....)
No I want to create reports where I can filter for date and course etc.
What I did for now is. I created a Statistic class where I can pass the date, playerid, roundid, courseid in the construct. The construct will query all the rounds played, matching those filters.
Then, foreach statistic I made a public function ex. scoring_average, greenhit_percantage, putts_per_round, putts_per_greeninregulation etc. there are about 15 stats.
So my question is: is that right what I'm doing here? because I have about 15 functions just to calculate statistics.
Please give me some advice if you have a better solution.
Thank you
class Statistic {
/**
* The table associated with the model.
*
* #var string
*/
public $rounds = [];
public function __construct($user_id, $roundid = null, $start = "2000-01-01", $end = "2030-01-01", $courseid = 0){
$this->rounds = Round::where('user_id', '=', $user_id)->get();
}
public function score(){
if(count($this->rounds) > 0){
$avg = 0;
foreach($this->rounds as $round){
$scores = Score::where('round_id', '=', $round->id)->get(['score']);
foreach($scores as $score){
$avg += $score->score;
}
}
return $avg / count($this->rounds);
} else {
return "N/A";
}
}
public function fir(){
if(count($this->rounds) > 0){
$fairway = [];
foreach($this->rounds as $round){
$scores = Score::where('round_id', '=', $round->id)->get(['fir']);
foreach($scores as $score){
if($score->fir != 0){
array_push($fairway, $score->fir);
}
}
}
$hits = array_count_values($fairway);
//unset($hits[0]); //unsets par 3 with value 0
return self::percArray($hits);
return $perc;
} else {
return "N/A";
}
}

declare variable to store linq entity for conditional statements

I am trying to look up record using if I have the key then use Find if not use Where
private ApplicationDbContext db = new ApplicationDbContext();
public bool DeactivatePrice(int priceId = 0, string sponsorUserName = "")
{
var prices = db.BeveragePrices;
// if we have an id then find
if (priceId != 0)
{
prices = prices.Find(priceId);
}
else
{
prices = prices.Where(b => b.UserCreated == sponsorUserName);
}
if (prices != null)
{
// do something
}
return true;
I get the following error for
prices = prices.Find(priceId);
Cannot convert app.Model.BeveragePrices from system.data.entity.dbset
I am copying the pattern from this answer but something must be different.
Seems you forgot to put a predicate inside the Find function call. Also you need to do ToList on the collection. The second option is a lot more efficient. The first one gets the whole collection before selection.
Another note commented by #Alla is that the find returns a single element. So I assume another declaration had been made for 'price' in the first option I state down here.
price = prices.ToList.Find(b => b.PriceId == priceId);
Or
prices = prices.Select(b => b.PriceId == priceId);
I assume the field name is PriceId.

Is this a valid way to check if db_row exists?

I am working with Zend and I needed to check whether a row in the DB already exists (A simple solution to get rid of the duplicate key error I was getting). I tried several things but nothing seemed to work... (for example the Zend_Validate_Db_NoRecordExists method)
So I wrote the following the code and I was wondering if this is a valid way to do it, or if I should do things differently:
In the model:
$where = $condition = array(
'user_id = ' . $user_id,
'page_id = ' . $page_id
);
$check = $this->fetchRow($where);
if(count($check) > 0) {
return null;
}else{
// Here I create a new row, fill it with data, save and return it.
}
And then in my view:
if($this->result != null) { /* do stuff */ }else{ /* do other stuff */ }
It does work but it does seem to take more time (duh, because of the extra query) and I am a bit unsure whether I should stick with this..
Any recommendation is welcome :)
Assuming you have coded your function in your controller
$row = $this->fetchRow($where); //If no row is found then $row is null .
if(!$row)
{
$row = $dbTb->createNew($insert); //$insert an associative array where it keys map cols of table
$row->save();
$this->view->row_not_found = true;
}
return $row;
In your view you can do this
if($this->row_not_found)
{
}else {
}

Symfony form with doctrine table other than getTable()->find() is not working

I get a really anoying error when I try to edit an entry from a table, in tutorial they always use getTable()->find(), but I need to verify that the person logged in is the owner of that entry here what I did:
In the action:
public function executeEdit(sfWebRequest $request)
{
$id = $request->getParameter('id');
$userid = $this->getUser()->getGuardUser()->getId();
$ad = Doctrine_Core::getTable('BambinbazarArticles')->getMyAd($id, $userid);
$this->forward404Unless($ad, sprintf('Object bambinbazar_articles does not exist (%s).', $request->getParameter('id')));
$this->form = new BambinbazarArticlesForm($ad);
}
In the model:
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid);
return $q->execute();
}
I tried it with and without the ->execute(), did doctrine clean, cleared cache, rebuilded model,
Always get the same error 'The "%s" form only accepts a "%s" object.
If I use the Doctrine_Core::getTable('BambinbazarArticles')->find() it work, but of course, i need more than that..
I am becoming crazy over this.
execute() can return multiple rows; effectively you're getting a recordset back, rather than the individual object that your form is expecting. Try fetching a single object, using, e.g.:
return $q->execute()->getFirst();
or
return $q->fetchOne();
Its probably because your query is returning a Doctrine_Collection, not the actual Doctrine_Record youre expecting. Instead of execute use fetchOne.
public function getMyAd($id, $userid)
{
$q = $this->createQuery('c')
->where('c.id = ? ', $id)
->addWhere('c.userid = ? ', $userid)
->limit(1);
return $q->fetchOne();
}