I have a problem with Laravel 7 Eloquent. I have 2 tables joined by many to many relation. Table user is connected to PaymentModule by pivot table PaymentModuleUser. I need to use where on pivot table on statement is_active = 1. When i use toSQL() in my model SQL returns good results but when i check my Eloquent Query in Controller, data that i revicive ignore my wherePivot method (return all data from table ignoring is_active = 1 field subscribers = null and get me this user.. I must do it if my pivotWhere = null dont show this user). Could you point me where i get wrong with my code?
My UserTable model:
public function subscriber(){
return $this->belongsToMany(PaymentsModule::class, 'payment_module_user', 'user_id')->withPivot('is_active');
}
MyController:
$users = User::with(['subscriber'=>function($query)
{
$query->wherePivot('is_active','=', 1);
}])->get();
print_r($users);
Try with
$users = User::with('subscriber' => function($query) {
$query->where('payment_module_user.is_active', 1);
})->get();
print_r($users);
The pivot table is already joined by eloquent, so just start using it
Found it here.
In your controller, try using this
$query->wherePivot('is_active', 1);
Instead of,
$query->wherePivot('is_active','=', 1);
Related
I have a simple db table:
create table if not exists players
(
id bigint,
name text,
results text[]
);
Now I would like to create select query, where I want only rows with passed results. So I created a scala code with doobie:
def getPlayers(id: Int, result: String): Query[Int] = {
sql"select id from players where results ? $result".query[Int]
}
But it didn't work as expected. My question is how to select from array column in postgresql? Currently I have results as an array, but I could change it to jsonb if it is easier.
You can use the following query:
select id from players where $result = any(results);
You can find more information here:
https://www.postgresql.org/docs/current/functions-comparisons.html
I want to write a query in Laravel to retrive all the posts that a particular user has viewed. The user_id and the post_id is saved in the table named WatchHistory.
SELECT *
FROM Post
WHERE post_id = (
SELECT post_id
FROM WatchHistory
WHERE user_id = $user_id
);
I tried the following :
$posts = Post::whereIn('post_id', function($query){
$query->select('post_id')
->from(with(new WatchHistory)->getTable())
->where('user_id',$user_id);
})->get();
But it gives me an error that the variable user_id is not defined.
You should try this :
POST::whereIn('post_id', function($query) use($user_id){
$query->select('post_id')
->from(with(new WATHCHISTORY)->getTable())
->where('user_id',$user_id);
})->get();
Hope this work for you !!!!
Try this one,
If your user's id is in variable $user_id, you can do it like,
DB::table('post')->whereIn('post_id',
DB::table('watchhistory')->where('user_id',$user_id)->pluck('post_id')
)->get();
I have three tables. I want to display all data from cms_planner table together with Topic Name from cms_topic table. To achieve that, I need to go through the cms_subject table.
I want to use belongsToMany but I already have cms_subject table that holds the foreign key for cms_planner and the foreign key for cms_topic. The table name does not represent pivot key.
I also want to use hasManyThrough but it doesn't work. I'm thinking to inverse the hasManyThrough.
How can I achieve that?
1. CmsPlanner
i. planner_id
ii. subject_id
iii. date_start
2. CmsSubject
i. subject_id
ii. topic_id
3. CmsTopic
i. topic_id
ii. topic name
In CmsPlanner model
public function subject(){
return $this->hasManyThrough(
'App\CmsTopic',
'App\CmsSubject',
'topic_id', 'topic_id', 'planner_id');}
In CmsPlanner controller
CmsPlanner::with('subject')->get();
Add this relation on CmsSubject
public function cmsTopic()
{
return $this->belongsTo('App\Models\CmsTopic', 'topic_id', 'topic_id');
}
then add following relation on CmsPlanner
public function cmsSubject()
{
return $this->belongsTo('App\Models\CmsSubject', 'subject_id', 'subject_id');
}
to get data
$cms_planner = CmsPlanner::with('CmsSubject')->where('id', $planner_id)->get();
'user' => $this->business->user
My goal is to create a query, macro or any solution that can do the task described below.
Lets say I have an access 2016 table named "student" with 12 records like this:
And then, lets say I have a second table named "matchme" with 4 records like this:
I need to find a way to
=> first, create a query that returns result of "graduation_date" are equal to Date "1/31/2017" from Table "student" .
=> second, from the result returned from first step, create a query that compare "email" from "student" table with "email" from "matchme" table, and return the [matched] record result.
So the desired result would be:
since the email gary#xxx.com and thomas#xxx.com exist in both tables.
How can I create a query like this?
you can download my access file from here: experiment.accdb
Simple:
select * from student
inner join matchme on student.email = matchme.email
where student.graduation_date = '1/31/2017'
Looking to your data sample you need a join on date and name between the two tables
select * from student
inner join matchme on student.graduation_date = matchme.graduation_date
and student.email = matchme.email
where student.graduation_date = '1/31/2017'
I have two tables A & B, and B has a many:1 relationship with A.
When querying rows from A I'd also like to have corresponding B records returned as an array and added to the result array from A, so I end up with something like this:
A-ROW
field
field
B-ITEMS
item1
item2
item3
Is there a clean way to do this with one query (perhaps a join?), or should I just perform a second query of B on the id from A and add that to the result array?
It would be more efficient to join table B on table A. It will not give you the data in the shape you are looking for. But you can iterate over this result and build the data into the desired shape.
Here is some code to illustrate the idea :
// Join table B on table A through a foreign key
$sql = 'select a.id, a.x, b.y
from a
left join b on b.a_id=a.id
order by a.id';
// Execute query
$result = $this->db->query($sql)->result_array();
// Initialise desired result
$shaped_result = array();
// Loop through the SQL result creating the data in your desired shape
foreach ($result as $row)
{
// The primary key of A
$id = $row['id'];
// Add a new result row for A if we have not come across this key before
if (!array_key_exists($id, $shaped_result))
{
$shaped_result[$id] = array('id' => $id, 'x' => $row['x'], 'b_items' => array());
}
if ($row['y'] != null)
{
// Push B item onto sub array
$shaped_result[$id]['b_items'][] = $row['y'];
}
}
"... just perform a second query of B on the id from A and add that to the result array ..." -- that is the correct solution. SQL won't comprehend nested array structure.
To build on what Smandoli said--
Running the secondary query separately is more efficient because even if row data on the primary table (A) has changed, unchanged data on the secondary table (B) will result in a (MySQL) query cache hit assuming the IDs never change.
This is not necessarily true of the join query approach.
There will also be less data coming over the wire since the join approach will fetch duplicate data for the primary table (A) if the secondary table (B) has multiple rows associated with a single row in the primary table.
Hopefully anyone looking to do this (relatively) common type of data retrieval may find this useful.