Pluck primaryKey from relationship between same table - php

Cursos has a many-to-many relationship with Cursos and i want to get only the primaryKey from the related Cursos.
$curso = Curso::with(['thumb','interna','area','cursos_relacionados' => function($query){
$query->pluck('curso_id');
}])->find($curso_id);
The problem: Column 'curso_id' in field list is ambiguous.
I could do this:
DB::table('cursos_has_cursos_relacionados')->select('curso_relacionado_id')
->where('curso_id','=',$curso_id)->pluck('curso_relacionado_id')->toArray();
But i would like to know if its possible and how to add a alias to the with() method and use the first sample of code.
UPDATE
This is the relation
public function cursos_relacionados(){
return $this->belongsToMany('App\Model\Curso','cursos_has_cursos_relacionados','curso_id','curso_relacionado_id');
}

The problem: Column 'curso_id' in field list is ambiguous.
You need to specify table: 'thumb.curso_id' or the table you want.

Unfortunately, i couldn't find anything about setting a alias on the with() method. But, if anyone finds himself here, loking for the same anwser. Try the following code, it should work just fine
$curso = Curso::with(['thumb.media_root','interna.media_root','objetivos_media.media_root','area'])->find($curso_id);
$curso->cursos_relacionados = DB::table('cursos_has_cursos_relacionados')->select('curso_relacionado_id')->where('curso_id','=',$curso_id)->pluck('curso_relacionado_id')->toArray();

Related

Search in Related Model using GridView Filter Field

Question:
Let's Say i have two tables,
Table1 Table2
-authorId -username
As of now my sql query on search model looks like this,
->andFilterWhere(['"Table1"."authorId"' => $this->authorName]);
It only helps to search and filter using the authorID.
Expected Result
I would like to search based on the authorname instead of authorId.
I faced similar difficulty in reflecting data in view but i was able to fix it with following getter function in base model.
public function getAuthorName() {
return $this->author->username;
}
Thanks in Advance,
First, add a custom attribute to your search model
public $username
define a relation to your author table inside the model
public function getAuthor() {
return $this->hasOne(Author::className(),['id'=>'authorId']);
}
in your gridview replace the authorId column with
`author.username`
and use the following to compare
$query->andFilterWhere(['like', '{{%Table2}}.username',$this->username]);
and yes make sure you join you searchmodel query with the author table in the start of search function
->joinWith('author')
Assuming authorId is a FK to table2, and you have previoulsy joined table2 to table1, you can do the following:
->andFilterWhere(['table2.username' => $this->authorName]);

How to get the count of Belongsto in Laravel?

I want to get the count of the elements of materials count.
SubCategory:
public function materials(){
return $this->hasMany('App\Material');
}
Materials:
public function subcategories(){
$this->belongsTo('App\SubCategory','SubCategoria_id');
}
I want to get the count of the elements that have the subcategory_id
'quantidade' => $subcategory->material->count()
I'm getting error in 1054 Unknown column 'material.subcategory_id'
You should use the relationship to count. This will count the items using the DB. You should use the function like this:
'quantidade' => $subcategory->materials()->count()
And in the model, you have to inform the id in hasMany too:
public function materials(){
return $this->hasMany('App\Material' ,'SubCategoria_id');
}
You should also notice that it would be better if you name yours classes and variables according to Laravel patterns.
Does your material table have a subcategory_id column? This error could indicate it doesn't exist, therefore it's failing when you try the relationship.
As long as the column exists, the relationship should be valid and you should be able to count the results.
Since you're using a custom foreign key, you need to specify it. So, change the relation to:
public function materials()
{
return $this->hasMany('App\Material', 'SubCategoria_id');
}
And then use the proper relationship name:
$subcategory->materials()->count()

How to set alias table name in Laravel table model

I have this query builder in Laravel:
$obj_table = MyTable::get();
Now, how to make my MyTable to have alias name?
The reason I need this, I need to use with() and Joining with my another tables.
Anyone got the same problems with me?
Thanks!
From laravel documentaion
You may also alias the relationship count result, allowing multiple counts on the same relationship:
$posts = Post::withCount([
'comments',
'comments AS pending_comments' => function ($query) {
$query->where('approved', false);
}
])->get();
For more information have a look at
https://laravel.com/docs/5.4/eloquent-relationships
Cheers,
Hope this helps

Laravel Restful Controller ID

So to explain my issue, whenever i am connecting to the database with Laravel it will default search for the id column as "id".
If i name my column jobID for example, i would like to controller to search for "jobID" instead of just "id". I could just change all of my tables ID columns to "id" however this causes issues when you use Laravel's left joins as it will take the latest id column as the actual id column.
Heres my join:
$jobs = Job::leftJoin('occupational_areas', function($join) {
$join->on('jobs.occupationalArea', '=', 'occupational_areas.id');
})->get();
However Restful controller default to "id" and that is what i'm asking, how do i change the default "id" to becomes something more custom like jobID
Try using this left join
$jobs = Job::select('occupational_areas.id as occ_id', 'jobs.id as jobs_id', your required values)
->leftJoin('occupational_areas', 'jobs.occupationalArea', '=', 'occupational_areas.id')
->get();
comment for errors
Turns out the easiest way to do this is by setting:
protected $primaryKey = 'jobID';
Into your model.
I am pretty sure Ronser also had it right with his method. Either will work.
Thanks Ronser!

Kohana add function return province name

I'm back again for another question, i'm trying and trying. But i can't get it fixed.
This is my issue;
I have a database table, with a ProvinceID this can alter from 1 to 12. But it's an ID of the province. The provinces are stored with the value pName in the table Provinces
I have the following code to alter the table, and join it with the preferences table
$veiling = ORM::factory('veilingen')
->select('veilingvoorkeur.*')
->join('veilingvoorkeur', 'LEFT')
->on('veilingen.id', '=', 'veilingvoorkeur.vId')
->find_all();
$this->template->content = View::factory('veiling/veilingen')
->bind('veiling', $veiling);
It displays correctly, in the view i have;
echo '<div class="row">';
foreach($veiling as $ve)
{
echo $ve->provincie;
}
?>
</div>
it displays the provincie id; but i want to add a function to it; So it will be transformed to a province name. Normally i would create a functions.php file with a function getProvince($provinceId)
Do a mysql query to grab the pName value from Provinces and that is the job. But i'm new to kohana. Is there an option to turn the province id to province['pName'] during the ORM selection part, or do i have to search for another solution. Which i can't find :(
So. Please help me on the road again.
Thanx in advance.
Kind regards,
Kevin
Edit: 1:08
I've tried something, and it worked. I used ORM in the view file, for adding a function;
function provincie($id){
$provincie = ORM::factory('provincies', $id);
return $provincie->pName;
}
But i'm not glad with this way of solution, is there any other way? Or am i have to use it this way?
Check out Kohana's ORM relationships. If you use this, you could access the province name by simply calling:
$ve->provincie->name;
The relationship definition could look something like:
protected $_belongs_to = array(
'provincie' => array(
'model' => 'Provincie',
'foreign_key' => 'provincie_id'
),
);
Note that if you have a table column called provincie the relationship definition I give above will not work. You'd either have to change the table column to provincie_id or rename the relationship to e.g. provincie_model.
The output you describe when you do echo $ve->provincie; suggests that you store the ID in a column called provincie, thus the above applies to you.
I'd personally go for the first option as I prefer accessing IDs directly with an _id suffix and models without any suffix. But that's up to you.
Edit: If you use Kohanas ORM relationships you could even load the province with the initial query using with() e.g:
ORM::factory('veiling')->with('provincie')->find_all();
This could save you hundreds of extra queries.

Categories