GroceryCrud set a n-n relation with where clause - php

I have three tables (simplified) which are:
And I have to display all houses for each user.
In my controller I have a function like this:
public function create_houses_table($usr_id)
{
$crud = new grocery_CRUD();
$crud->set_language("italian");
$crud->set_theme('datatables');
$crud->set_subject('Casette');
$crud->set_table('tbl_houses');
$crud->set_relation_n_n('Casette',
'tbl_users_houses',
'tbl_users',
'house_id',
'user_id',
'usr_name',
NULL,
array('user_id' => $usr_id));
...
}
and what I get is this:
Every time I select a user from the combo I need to refresh my list filtering on usr_id...but I get always all the houses.
What I'm wrong?

This is not the intended usage for set_relation_n_n (it will show all the user houses in one field inside the user row).
What you want can be better done listing from tbl_users_houses, filtering by client with $crud->where() and linking with the other tables with two simple relations.

If I understand correctly you are trying to fetch only the records for the logged in User... and u have multiple users per house, hence the n-n relation.
I also faced this problem and here's what I did.
$myprojects = $this->admin_model->get_employee_projects($this->user_id);
$myprojectids = array_column($myprojects, 'id');
//get only one column from the multi-dimensional array
$crud->where("`projects`.id IN", "(" . implode(",", $myprojectids) . ")", false);
// the false disables escaping
$crud->set_relation_n_n('assigned_employees', 'project_employees', 'employees', 'project', 'employee', 'name');
//Only so it also still shows the name of Users assigned
So basically projects here is like houses, and I am using the WHERE IN clause to filter the records based on the projects I get from my model method...

Related

Get data from multiple sql tables using eloquent with laravel

What i want to achieve?
Show user which pacts he is following.
What I am trying
I have designed two tables which are 'pacts' & 'pacts_follwers'
Table 'pacts' has the details of all the pacts
Table 'pacts_follwers' has details of users following a particular pact.
These links will give you the images of both the tables
For Schema Refer Images
So how to get pacts that user is following.
What I have tried?
Sql Query
SELECT pacts.*, (SELECT pactsid FROM pacts_follwers WHERE pacts.id = pacts_follwers.pactsid
and pacts_follwers.userid = 2 ) as pactID FROM `pacts`
Sql query Result
This query will give pactId some value, where the value is null means the user is not following that pact. If this is the solution then i would need Eloquent for this which i am unable to make.
1st table pacts
id
title
about
created_at
updated_at
pactsImage
2nd table pacts_follwers
id
pactsid
userid
created_at
updated_at
Controller Code
$pacts = DB::select("SELECT pacts.*, (SELECT pactsid FROM pacts_follwers WHERE pacts.id =
pacts_follwers.pactsid and pacts_follwers.userid = ".Auth::id()." ) as pactID FROM `pacts`");
You need to setup hasManyThrough relationship for User and Pact.
class User extends Model {
public function pacts() {
return $this->hasManyThrough(
Pact::class,
PactFollower::class
'userid',
'pactsid'
);
}
}
I don't fully understand if you want to achieve "get user's all pacts" or "if pact is followed by user". Either way, you need to setup related relationships.
Or really simple (and not efficient way)
class Pact extends Model {
public function followers() {
return $this->hasMany(PactFollower::class, 'pactsid')
}
}
Now you can use something like
$userIdsForPact = Pact::followers()->pluck('userid');
if ($userIdsForPact->has($user->id)) {
// your operation
}
Edit: For "if pact is followed by user", you need to setup belongsToThrough relationship. It doesn't come out of the box with Laravel but staudenmeir/belongs-to-through package should serve you well.
After setting the relationship properly, you can use something like this.
Pact::with('user')->get();
Or add some methods in your Pact model:
public function followedByUser($user) {
return $this->users->has($user);
}

OctoberCMS filter Relation Widget based from currently selected record

The title says it all, but to give an example. I have a Member record and a Group. A member can have memberships in many groups and a group can have many members. (So that's many to many and I would have a pivot table for it.)
Now, each group has membership grades. E.g., (Free, Freemium, Premium, Super Premium). So the membership_grade shall belong to the pivot table, right? But here's the problem, not all groups share the same grades. Some might have Free and Freemium only, some might have all.
In the fields.yaml of the Membership pivot model, I defined the membership_grades as a Relation Widget, like this:
pivot[grade]:
label: Membership Grade
span: full
type: relation
nameFrom: name
And in its relationship in Membership.php like this:
public $belongsTo = [
'grade' => [
'Acme\Models\Grade',
]
];
Obviously, this will expose ALL grades, since I'm pulling data from the Grade model. What I want is to expose the grades that is just available on that group, not all.
What I've thought to do (but I didn't, because it seemed impossible) is to try to pull data from the grades relationship of the Group, but how am I suppose to do that? (Since Relation widget manages the relation of the Model, I cannot simply pull data from other sources just like that).
Also I've tried to do scopes but how am I suppose to pass the current Group I'm in? Since it is needed as the filter, like this:
// Membership.php
public $belongsTo = [
'grade' => [
'Acme\Models\Grade',
'scope' => 'filteredIt'
],
// added this relationship to try the scopes approach
'group' => [
'Acme\Models\Group'
]
];
// Grade.php
public function scopeFilteredIt($query, Membership $m)
// yes, the second parameter in the scope will be the
// current Membership model. I've tried it.
{
// this won't work, since we want the overall relation filter;
// an instance of Membership won't help.
// this would work if I can find a way to pass the
// current Group (record) selected, and get its grades, then use it here.
return $query->whereIn('id', $m->group->grades->pluck('id')->all());
}
Any thoughts?
I have noticed some post values during pivot model ajax call.
When you add new record and when your pivot model opens post values are like this
Array (
[_relation_field] => groups
[_relation_extra_config] => W10=
[foreign_id] => 1
[_session_key] => VrSCoKQrSkIsZNGIju5QIqpdbS3AADoGQRHAsv1e
)
So good thing is that we can now get foreign_id as it will be your selected group id
and we can use it at creation time and for update time you know we have relation so we use that.
public function scopefilteredIt($query, Membership $m)
{
// we are checking relation is there or not
if($m->group) {
// yes group is there we use it
return $query->whereIn('id', $m->group->grades->pluck('id')->all());
}
else {
// seems new record then use foreign_id
$foreign_id = post('foreign_id'); //<-this will be your selected group id
if($foreign_id) { // <- double check if its there
$group = Group::find($foreign_id);
return $query->whereIn('id', $group->grades->pluck('id')->all());
}
}
return $query;
}
please comment if you get any issue.
to check post
public function scopefilteredIt($query, Membership $m)
{
// will show flash message with post data array
$post = print_r(post(), true);
\Flash::success($post);
// we are checking relation is there or not
if($m->group) {
// yes group is there we use it
return $query->whereIn('id', $m->group->grades->pluck('id')->all());
}
else {
// seems new record then use foreign_id
$foreign_id = post('foreign_id'); //<-this will be your selected group id
if($foreign_id) { // <- double check if its there
$group = Group::find($foreign_id);
return $query->whereIn('id', $group->grades->pluck('id')->all());
}
}
return $query;
}

how to make fetching from two three model with clause and fetch selected fields in laravel [duplicate]

I have two tables, User and Post. One User can have many posts and one post belongs to only one user.
In my User model I have a hasMany relation...
public function post(){
return $this->hasmany('post');
}
And in my post model I have a belongsTo relation...
public function user(){
return $this->belongsTo('user');
}
Now I want to join these two tables using Eloquent with() but want specific columns from the second table. I know I can use the Query Builder but I don't want to.
When in the Post model I write...
public function getAllPosts() {
return Post::with('user')->get();
}
It runs the following queries...
select * from `posts`
select * from `users` where `users`.`id` in (<1>, <2>)
But what I want is...
select * from `posts`
select id,username from `users` where `users`.`id` in (<1>, <2>)
When I use...
Post::with('user')->get(array('columns'....));
It only returns the column from the first table. I want specific columns using with() from the second table. How can I do that?
Well I found the solution. It can be done one by passing a closure function in with() as second index of array like
Post::query()
->with(['user' => function ($query) {
$query->select('id', 'username');
}])
->get()
It will only select id and username from other table. I hope this will help others.
Remember that the primary key (id in this case) needs to be the first param in the
$query->select() to actually retrieve the necessary results.*
You can do it like this since Laravel 5.5:
Post::with('user:id,username')->get();
Care for the id field and foreign keys as stated in the docs:
When using this feature, you should always include the id column and
any relevant foreign key columns in the list of columns you wish to
retrieve.
For example, if the user belongs to a team and has a team_id as a foreign key column, then $post->user->team is empty if you don't specifiy team_id
Post::with('user:id,username,team_id')->get();
Also, if the user belongs to the post (i.e. there is a column post_id in the users table), then you need to specify it like this:
Post::with('user:id,username,post_id')->get();
Otherwise $post->user will be empty.
For loading models with specific column, though not eager loading, you could:
In your Post model
public function user()
{
return $this->belongsTo('User')->select(['id', 'username']);
}
Original credit goes to Laravel Eager Loading - Load only specific columns
When going the other way (hasMany):
User::with(['post'=>function($query){
$query->select('id','user_id');
}])->get();
Don't forget to include the foreign key (assuming it is user_id in this example) to resolve the relationship, otherwise you'll get zero results for your relation.
In Laravel 5.7 you can call specific field like this
$users = App\Book::with('author:id,name')->get();
It is important to add foreign_key field in the selection.
If you want to get specific columns using with() in laravel eloquent then you can use code as below which is originally answered by #Adam in his answer here in response of this same question, the answer's main code is as below :
Post::with('user:id,username')->get();
So i have used it in my code but it was giving me error of 1052: Column 'id' in field list is ambiguous, so if you guys are also facing same problem
Then for solving it you have to specify table name before the id column in with() method as below code:
Post::with('user:user.id,username')->get();
I came across this issue but with a second layer of related objects. #Awais Qarni's answer holds up with the inclusion of the appropriate foreign key in the nested select statement. Just as an id is required in the first nested select statement to reference the related model, the foreign key is required to reference the second degree of related models; in this example the Company model.
Post::with(['user' => function ($query) {
$query->select('id','company_id', 'username');
}, 'user.company' => function ($query) {
$query->select('id', 'name');
}])->get();
Additionally, if you want to select specific columns from the Post model you would need to include the user_id column in the select statement in order to reference it.
Post::with(['user' => function ($query) {
$query->select('id', 'username');
}])
->select('title', 'content', 'user_id')
->get();
In your Post model:
public function userWithName()
{
return $this->belongsTo('User')->select(array('id', 'first_name', 'last_name'));
}
Now you can use $post->userWithName
There is another alternative you can eager load specific columns
public function show(Post $post)
{
$posts = $post->has('user')->with('user:id,name,email,picture')->findOrFail($post->id);
return view('your_blade_file_path',compact('posts);
}
In your Post model you should have user relationship also
public function user()
{
return $this->belongsTo( User::class, 'user_id')->withDefault();
}
Note: It is mentioned in Laravel docs.
https://laravel.com/docs/8.x/eloquent-relationships#eager-loading-specific-columns
Note that if you only need one column from the table then using 'lists' is quite nice. In my case i am retrieving a user's favourite articles but i only want the article id's:
$favourites = $user->favourites->lists('id');
Returns an array of ids, eg:
Array
(
[0] => 3
[1] => 7
[2] => 8
)
If you use PHP 7.4 or later you can also do it using arrow function so it looks cleaner:
Post::with(['user' => fn ($query) => $query->select('id','username')])->get();
I faced the same issue while using belongsToMany relationship with my user model (Laravel 8.x.x).
After a long search and trial and test method. I found out this answer
You have to make sure you are selecting the id's and any foreign keys that would be needed for the relationship from either side of that relationship. This allows Eloquent to match up parents to their children.
Original credit goes to https://stackoverflow.com/a/64233242/1551102
So I included
Groups::select('groupid')
...
And it worked like a charm. Although now I want to know how to hide the groupid field after fetching.
I know I can simply loop through the array and remove it. But is there any other method? potentially a simpler and better one.
You can also specify columns on related model at the time of accessing it.
Post::first()->user()->get(['columns....']);
You can try this code . It is tested in laravel 6 version.
Controller code
public function getSection(Request $request)
{
Section::with(['sectionType' => function($q) {
$q->select('id', 'name');
}])->where('position',1)->orderBy('serial_no', 'asc')->get(['id','name','','description']);
return response()->json($getSection);
}
Model code
public function sectionType(){
return $this->belongsTo(Section_Type::class, 'type_id');
}
Be careful that if you don't add the key column(s) it won't return anything. If you want to show only the username without the id you could instead define the $visible/$hidden properties within the Model, like so:
app/Models/User.php
protected $visible = ['username'];
Then it will retrieve only username column with:
Post::with('user')->get();
Hiding the key columns:
Alternatively you could hide the key column(s) and then retrieve only the columns you wish.
app/Models/User.php
protected $hidden = ['id'];
Specify which columns you want including the key or else it won't return anything, but this will actually only return the username, because id is $hidden.
Post::with('user:id,username')->get();
Now you can use the pluckmethod on a Collection instance:
This will return only the uuid attribute of the Post model
App\Models\User::find(2)->posts->pluck('uuid')
=> Illuminate\Support\Collection {#983
all: [
"1",
"2",
"3",
],
}
Try with conditions.
$id = 1;
Post::with(array('user'=>function($query) use ($id){
$query->where('id','=',$id);
$query->select('id','username');
}))->get();
So, similar to other solutions here is mine:
// For example you have this relation defined with "user()" method
public function user()
{
return $this->belongsTo('User');
}
// Just make another one defined with "user_frontend()" method
public function user_frontend()
{
return $this->belongsTo('User')->select(array('id', 'username'));
}
// Then use it later like this
$thing = new Thing();
$thing->with('user_frontend');
// This way, you get only id and username,
// and if you want all fields you can do this
$thing = new Thing();
$thing->with('user');
EmployeeGatePassStatus::with('user:id,name')->get();

updating related tables from a controller laravel

Hi I’ve a users and education table. A user can have multiple school or college. So its one to many relationship. education table has school, from_year, to_year and user_id (fk) I want to update the user table as well as education table from a PUT request to users/{id} with email,school, from_year, and to_year fields.
// UsersController.php
public function update(Request $request, $id)
{
$user = User::find($id);
if (!$user) {
return $this->respondNotFound('User not found');
}
$input = $request->all();
$input = array_filter($input, 'strlen');
//$user->update($input);
//Get array of school records
// $user->educatoion->push($records) // don't know what will come here to update the education table
// or may be $user->push(); // don't know
return $this->respond([
'data' => $user,
]);
}
Try to keep it as simple as possible.
If this is your first time updating multiple tables at once, draw up a diagram of the process. This way you can identify the correct order of updates.
Take care to note any formatting that has to done on each value.
Laravel has some great functionality in regards to binding input to a model using ->update($data)
However, when binding to multiple models, you might run into issues with duplicate field names.
Update:
To create a education row from the $user model:
$education = new Education(array('school' => 'Harward', 'from_year' => 1999, 'to_year' => 2016));
User::find($id)->education()->save($education);

How to use grocery set_relation function to display content from two different tables in different columns

I have to tables with these schema:
users(id, name, email)
user_details (id, user_id, physical_address, otherinfo)
I would like to display all contents of both tables in one grid using grocery crud
when i try to use set relation on the first table as shown: Note: I have reducted the part that does the rendering of the view;
$crud = new grocery_CRUD();
$crud->set_table('users');
$crud->set_relation('id', 'user_details', '{physical_address} + {otherinfo}');
the values of the id field as well as the referenced table don't appear in the grid, so it does not seem to work when using primary keys.
So I decided to start with the contents of the second table like so:
$crud = new grocery_CRUD();
$crud->set_table('user_details');
$crud->set_relation('user_id', 'users', '{name} + {email}');
This works, but the problem is that the values appear in one column in the grid. I would like to know how i can separate them to different columns and make them editable in separate input fields.
my way kinda ridiculous,
if i were really need the field to be separated, i might use callback_column then use active records to return the value using $row->user_id, and callback each record
just like:
return $this->some_model->get_name($row->user_id); for name field
and
return $this->some_model->get_name($row->user_id); for email field
but, as i tested with some dummy records, it can't be sorted, (i dont know if anyone could)
There is no direct way to show multiple columns but i found an work around for this problem.
here is how
set name column as follows.
$crud->columns('name','email'); // define all required columns
$crud->callback_column(unique_field_name('user_id'),array($this,'callback_set_user_name'));
function unique_field_name($field_name)
{
return 's'.substr(md5($field_name),0,8);
}
public function callback_set_user_name($value, $row)
{
$row->full_name = $row->s447d3092; // before getting to know s447d3092 key return json_encode($row); you will key pair with {name} + {email} ex: {"s447d3092":"shiva + shiv#gmail.com"}
return explode("+",$value)[0]; // here you will have only name
}
$crud->callback_column('email',array($this,'callback_set_email'));
public function callback_set_email($value, $row)
{
return explode("+",$row->full_name)[1];
}
I am 100% sure this will help you

Categories