I have a table called emails, that has a pivot table and in that pivot table there is a column called "hash". Is there away to email that that hash belongs too?
I have tried this,
$email = Email::with(array('projects' => function($query) use($id) {
$query->where('hash', '=', $id);
}))->get();
But this returns all the rows from the email table and not just the one that matches the hash. Is there a way to search the pivot table and get back the row that relates from the email table?
When you define the projects method in your Email class you can add the pivot columns to the model by using the withPivot method:
public function projects()
{
return $this->belongsToMany('Project')->withPivot('hash');
}
You can then use it in the following way:
$email = Email::with(['projects' => /* ... */])->get();
foreach ($email as $item) {
echo $item->title; // regular field on `email`
echo $item->pivot->hash; // field on the pivot table
}
Related
I have a Many To Many relationship between User & Wallet Models:
Wallet.php:
public function users()
{
return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id')->withPivot('balance');
}
User.php:
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
And the pivot table user_wallet goes like this:
Then at the Controller, I need to access the balance field:
public function chargeWallet(Request $request, $wallet, $user)
{
// $wallet is wallet_id (2) & $user is user_id (373)
$bal = Wallet::with("users")
->whereHas('users', function ($query) use ($user) {
$query->where('id',$user);
})->where('id', $wallet)->first();
dd($bal->balance);
}
But now I get null as the result of dd($bal->balance) !!
So what is wrong here? How can I properly get the balance ?
Since it is a Many to Many relationships, you have Users attached to many Wallets, and Wallets attach to many Users. For each relation between a single Wallet and a single User: you have a pivot value (pivot relation). From your query, you'll retrieve Wallet with Users, each user's having the pivot relation value attached. So to retrieve the pivot table data (for each relation) you have to use a loop (added a with callback to make sure that only Users with matching user_id are eager loaded with the Wallets):
$bal = Wallet::with(["users"=>function ($query) use ($user) {
$query->where('user_id',$user);
}])
->whereHas('users', function ($query) use ($user) {
$query->where('user_id',$user);
})->find($wallet);
To avoid repeating same callback (where user_id =) you can assign it to variable:
$callback = function ($query) use ($user) {
$query->where('user_id',$user);
};
then use it in your query:
$bal = Wallet::with(['users' => $callback])
->whereHas('users', $callback)->find($wallet);
and then use a foreach loop:
foreach ($bal->users as $value){
dd($value->pivot->balance);
}
or
if you only want to return the pivot value for the first User of the first Wallet of your query, then:
$user = $bal->users->first();
dd($user->pivot->balance);
I have 3 tables :legalpursuit , guarantors, guarantors_legalpursuit. and I have Many To Many Relationships in my project.
I save legalpursuit_id in legalpursuit / guarantors_id in guarantors / and both of them in guarantors_legalpursuit.
I am using the laravel 8.
how can I show every post's tags ? how can I select data from tag_post table?
I use it as follows. but it does not get the data.
it's my Legalpursuit model:
public function guarantorses()
{
//return $this->belongsToMany(RelatedModel, pivot_table_name, foreign_key_of_current_model_in_pivot_table, foreign_key_of_other_model_in_pivot_table);
return $this->belongsToMany(Guarantors::class, 'guarantors_legalpursuit', 'legalpursuit_id', 'guarantors_id');
}
it's my Guarantor model:
public function legalpursuits()
{
//return $this->belongsToMany(RelatedModel, pivot_table_name, foreign_key_of_current_model_in_pivot_table, foreign_key_of_other_model_in_pivot_table);
return $this->belongsToMany(LegalPursuit::class,'guarantors_legalpursuit','guarantors_id', 'legalpursuit_id');
}
and it's my controller :
public function edit(LegalPursuit $legalPursuit, $id)
{
$user = Auth::user();
$data = LegalPursuit::find($id);
$guarantors = $data->guarantorses()->orderBy('name')->get();
$lawyers = $data->lawyers()->orderBy('name')->get();
dd($guarantors);
$filesPursuit = LegalPursuit::find($id)->files;
$getLawyersLeft = DB::table('users')->where('user_type', '2')
->where('active', '1')
->where('deleted', '0')
->take('5')
->get();
return view('pages.legalpursuit.edit', compact('data', 'getLawyersLeft', 'filesPursuit', 'user'));
}
no table name is different and it actually follows exactly;
protected $table = 'guarantors';
The fields of the table are as follows;
table name; guarantors
field: ID
field: name
pivot tablo name and details;
table name; guarantors_legalpursuit
id;
guarantors_id
legalpursuit_id
I can also do the adding process successfully as follows.
$guarantorArray = $request->input('GUARANTORS');
//$GuarantorsID = Guarantors::find($guarantorArray);
$data->guarantorses()->attach($guarantorArray);
but I can't pull relational data. it does not give an error. but although there is data in the table, the array feels empty.
I'm using datatables from yajra datatables and I have a problem.
I have a datatable where I obtain certain columns from other tables, for example the column "customer" is obtained through a relation from another table
But when I press the sort by customer button, the IDs change to the ID of the table where the relation belongs
This generates errors in the buttons that I have on the right since these IDs do not exist in the "meos" table, only in the "locations" table that is in the relation
How can I make it sort while keeping the same ID it had?
I want to always keep as order criteria the ID of the table I am with, which is the "meos" table belonging to the "meo" class
This is my query
public function query()
{
$languageId = Auth::user()->language_id;
return Meo::with(['businessType' => function ($query) use ($languageId) {
$query->with(['businessTypeDescriptions' => function ($subQuery) use ($languageId) {
$subQuery->where('language_id', '=', $languageId);
}]);
}])->with('location');
}
this is my function getcolumns
protected function getColumns()
{
return [
Column::make('id')->addClass('text-center')->title(__('digestReport.columns.id')),
Column::make('location.location_name')->addClass('text-center')->title(__('digestReport.columns.customer')),
Column::make('businessType')->addClass('text-center')->title(__('digestReport.columns.business_type'))->searchable(false),
Column::computed('action')->exportable(false)->printable(false)->width(160)->addClass('text-center')->title(__('digestReport.columns.actions')),
];
}
please, I need help.
Thanks :)
Try below code. Add ->select() statement
public function query()
{
$languageId = Auth::user()->language_id;
return Meo::with(['businessType' => function ($query) use ($languageId) {
$query->with(['businessTypeDescriptions' => function ($subQuery) use ($languageId) {
$subQuery->where('language_id', '=', $languageId);
}]);
}])->with('location')->select('meo-table.*');
}
Replace meo-table with your database table for Meo::class
I have three tables:
email_accounts (list of business emails)
-------------
id
email
sender_name
users
------
id
name
email
email_accounts_users
--------------------
email_account_id
user_id
And the eloquent relationship is declared as:
User
------
public function emailAccounts()
{
return $this->belongsToMany(EmailAccount::class,'email_accounts_users');
}
EmailAccount
------------
public function users()
{
return $this->belongsToMany(User::class,'email_accounts_users');
}
I am trying to fetch rows from email_accounts that belongs to current user.
This could be correctly fetched as:
$email_acc = \DB::table('email_accounts')
->join('email_accounts_users', 'email_accounts_users.email_account_id', 'email_accounts.id')
->join('users', 'users.id', 'email_accounts_users.user_id')
->select('email_accounts.*')
->where('user_id',auth()->user()->id)
->get();
dd($email_acc);
However, I am trying to get with laravel eloquent model.
So, I tried as follows:
$email_acc = EmailAccount::with(['users' => function(){
$query->where('users_id',auth()->user()->id)
}])->get();
dd($email_acc);
However, its returning all the emails from email_accounts, rather its filtering the data from users table and sending only the currently logged in user. from users table.
However, my requirement is to fetch emails form email_accounts that belong to currently logged in users.
Like
Try This
$email_acc = EmailAccount::whereHas('users', function($query) {
$query->where('id',auth()->user()->id);
})
->get();
dd($email_acc);
It will return empty collection if the record doesn't exixts
or you can also fetch using logged in user instance
$user = auth()->user();
return $user->emailAccounts;
Make sure you defined a perfect relationship
Read Querying Relationship Existence
Specify foreign keys as follows
public function emailAccounts()
{
return $this->belongsToMany(EmailAccount::class,'email_accounts_users', 'id', 'email_account_id' );
}
EmailAccount
------------
public function users()
{
return $this->belongsToMany(User::class,'email_accounts_users', 'id', 'user_id');
}
I'm trying to fetch data from my DB based on the value in my pivot table.
These are my tables:
uploads
-> id
-> name
-> type
emails
-> id
-> email
upload_emails
-> id
-> upload_id
-> email_id
-> url
Now for example I have the following url: 1234
How can I select the upload that is attached to the pivot table 'upload_email'
where the url value in the pivot table matches 1234
I had the following
Upload::emails()->wherePivot('url', $key)->get();
But that's not working at all. I do have the relations set up in my model etc...
EDIT:
After the suggested answer I'm pretty close. This is what I have now:
return Upload::with(array('emails' => function($query) use ($key) {
$query->wherePivot('url', $key);
}))->get();
I have 9 uploads in my database. When I use the query above, it returns all uploads, but the emails are only included on the matching pivot url. But that's not what I want, I only want 1 upload. The one where the pivot url matches my value.
According to your tables all you need is to fix this:
Upload::emails()->wherePivot('url', $key)->get(); // no url field on that table!
// change to:
Upload::find($id)->emails()->wherePivot('key', $key)->get();
// or if you want a collection then:
Upload::with(array('emails'=> function ($q) use ($key) {
$qwherePivot('key', $key);
}))->get();
// to fetch only those Upload models that have related email matching given 'key'
Upload::whereHas('emails', function ($q) use ($key) {
$q->where('upload_emails.key', $key);
})->get(); // add the above with(...) method to also load those emails
Eager loading constraints using the with method could be what you need:
Upload::with('email', function($q) use($key) {
$q->where('url', $key);
})->get();
check the docs for more info.
Try this:
$upload = Upload::with(array('email' => function($query) use ($key) {
// where is URL in the table? shouldn't it be 'key'?
$query->where('key', $key);
}))->get();
notes
As wherePivot and orWherePivot has become available, see here.
You have to add the additional column to your relationship like this:
public function emails(){
return $this->belongsToMany(...)->withPivot("key");
}
Supposedly with Laravel 4.1 you can add another method to your model:
$upload = Upload::emails()->wherePivot('key', $key)->get();