I would like to add some items in my db table pivot using eloquent ->attach but i don' t understand why it don't work:
I have 2 models (Salade=>(table 'salades' in DB) and Ingredient=>(table 'ingredients' in DB),
the pivot table is ingredient_salade( 3columns : id, ingredient_id,salade_id).
My Models:
class Ingredient extends Model
{
protected $table = 'ingredients';
protected $fillable = ['nom'];
public function Salades()
{
return $this->belongsToMany('App\Salade');
}
}
class Salade extends Model
{
protected $table = 'salades';
protected $fillable = ['nom','prix'];
public function ingredients()
{
return $this->belongsToMany('App\Ingredient');
}
}
SaladeController#Store
public function store(Request $request)
{
$this->validate($request, [
'nom' => 'required',
'prix' => 'required' ]);
$salade = $request->only(['nom', 'prix']);
// insert new salade in DB
$lanouvelleSalade = \App\Salade::create($salade);
//insert relation in pivot table
$lanouvelleSalade->ingredients()->attach([21,22,23]);
return redirect('salade')->withOk("Le Salade " . $request->input('name') . " a été modifié.");
}
the tables:
image of the tables
the new salade is insert in table salades but the relation in Pivot is not insert. Why?
change:
$lanouvelleSalade->ingredients()->attach([21,22,23]);
to:
$lanouvelleSalade->ingredients()->sync([21,22,23]);
replace your relation codes with this codes and check it:
Ingredient Class:
public function Salades()
{
return $this->belongsToMany('App\Salade','ingredient_salade','ingredient_id','salade_id');
}
And Salade Class:
public function ingredients()
{
return $this->belongsToMany('App\Ingredient','ingredient_salade','salade_id','ingredient_id');
}
let me know if you have any error
Related
I have two tables with a one to many relationship - gratitude_journal_entries and self_gratitudes. Multiple self gratitudes (which are submitted as text entries by the user) can apply to 1 gratitude_journal_entry. The data is passed to these two tables via a form.
I am trying to store the self gratitude text entries in an array and then pass these to the self_gratitude table along with the foreign key from the gratitude_journal_entries table.
The problem I'm having is I'm not sure how to take the input from the array and store this in the self_gratitude column.
Here are the columns for the gratitude_journal_entries table
Here are the columns for the self_gratitudes table
Here are the models and the store method in my controller
class SelfGratitudes extends Model
{
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
class GratitudeJournalEntry extends Model
{
protected $table = 'gratitude_journal_entries';
public $primarykey = 'id';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function selfGratitudes()
{
return $this->hasMany(SelfGratitudes::class);
}
public function store(Request $request)
{
$this->validate($request, [
]);
$gj_entry = new GratitudeJournalEntry;
$gj_entry->user_id = auth()->user()->id;
$gj_entry['entry_date'] = date('Y-m-d H:i');
$self_gratitudes = $request->has('self_gratitudes') ? $request->get('self_gratitudes') : [];
$tj_entry->save();
$gj_entry->selfGratitudes()->sync($self_gratitudes);
return redirect('/dashboard')->with('success', 'You submitted a new journal entry');
}
If you want to keep array in database you can use casting on your columns:
laravel document
class SelfGratitudes extends Model
{
protected $casts = [
'self_graitude' => 'array',
];
protected $table = 'self_gratitudes';
public $primarykey = 'id';
public function gratitudeJournalEntries() {
return $this->belongsTo(GratitudeJournalEntry::class);
}
}
I have this Many-to-Many relation Laravel Eloquent relationship
The Models are:
class Email extends Model //actually represent the email account
{
protected $table = 'emails';
protected $fillable = [
'user_id',
'name',
];
public function messages() {
return $this->belongsToMany(Message::class)->withPivot('email_subtype_id');
}
}
class Message extends Model //actually represent the email message
{
protected $table = 'messages';
protected $fillable = [
'subject',
'body ',
];
public function emails() {
return $this->belongsToMany(Email::class)->withPivot('email_subtype_id');
}
}
class EmailMessage extends Pivot //actually represent the pivot table
{
protected $table = 'email_message';
protected $fillable = [
'email_id',
'message_id',
'email_subtype_id',
];
public function email() {
return $this->belongsTo(Email::class);
}
public function message() {
return $this->belongsTo(Message::class);
}
//this is the relation to a third model called EmailSubtype
//I want to include this relation to the Pivot when using it
public function subtype() {
return $this->belongsTo(EmailSubtype::class, 'email_subtype_id');
}
}
class EmailSubtype extends Model //3rd Model need to be included with Pivot
{
protected $table = 'email_subtypes';
protected $fillable = [
'name'
];
public function pivotEmailSubtype(){
return $this->hasMany(Pivot::class, 'email_subtype_id');
}
}
I am able to do this in the Controller:
$email = Email::find(1);
foreach($email->messages as $message) {
$subtype_id = $message->pivot->email_subtype_id;
dd($subtype_id); //1 that relates to subtype: CC Email Account
//also I can get the name indirectly away from the relation as follows:
$subtypeName = EmailSubtype::find($subtype_id)->first()->name;
dd($subtypeName);
}
Here I am getting the email_subtype_id only by direct pivot relation but have to do extra work to get the related email sub-type name.
I need to get the email sub-type name [Directly] from the 3rd Model EmailSubtype relationship oneToMany [hasMany and belongsTo] that relates to Pivot model with EmailSubtype model using something like:
$message->pivot->subtypeName;
Any help please!
Use this:
public function messages() {
return $this->belongsToMany(Message::class)->withPivot('email_subtype_id')
->using(EmailMessage::class);
}
$message->pivot->subtype->name
I have Three models:
Language
Article
Category
The Article table has two foreign keys category_id and Language_id. Language-Model has "One to Many" Relationship with Article-Model, Similarly Category-Model has "One to Many" Relationship with Article-Model.
My Category model:
class Category extends Model
{
protected $fillable = [
'category_name',
];
public function articles(){
return $this->hasMany('App\Article');
}
}
My Language model:
class Language extends Model
{
protected $fillable = [
'language_name'
];
public function articles(){
return $this->hasMany('App\Article');
}
}
My Article model:
class Article extends Model
{
protected $fillable = [
'language_id','category_id','category_name','article_title',
'article_desc','source_from','source_url','video_link',
'audio_url','author_name','article_image_url','like_count'
];
public function languages(){
return $this->belongsTo('App\Language');
}
public function categories(){
return $this->belongsTo('App\Category');
}
}
How can I insert in the database using Laravel Eloquent?
$Article = new Article (
[
'article_image_url' => $img_url ,
'audio_url' => $audio_url,
'category_name'=>$category_name ,
'article_title'=>$request->article_title,
'article_desc'=>$request->article_desc,
'source_from'=>$request->source_from,
'source_url'=>$request->source_url,
'video_link'=>$request->video_link,
'author_name'=>$request->author_name,
'like_count'=>'0',
]
);
$language = new Language;
$category = new Category;
$language->articles()->save($Article);
language_id doesn't have a default value; it is foreign key.
When I want to save a reaction to a ticket I've three tables (in laravel):
-Tickets
-Reaction
-Reaction_Tickets (pivot table)
When I want to save a reaction I do it like this:
public function addReaction(Request $request, $slug)
{
$ticket = Ticket::whereSlug($slug)->firstOrFail();
$reaction = new reactions(array(
'user_id' => Auth::user()->id,
'content' => $request->get('content')
));
return redirect('/ticket/'.$slug)->with('Reactie is toegevoegd.');
}
But now of course it's not added to the pivot table. And I can't add it because I don't have a model of it. What's the right way of doing this?
EDIT:
-Tickets
public function reactions()
{
return $this->belongsToMany('App\reactions');
}
-Reactions
public function tickets()
{
return $this->hasOne('App\tickets');
}
From the Laravel documentation, you need to save and attach the Reaction to the Ticket:
$reaction = new reactions(array(
'user_id' => Auth::user()->id,
'content' => $request->get('content')
));
$reaction->save(); // Now has an ID
$tickets->reactions()->attach($reaction->id);
In your Ticket model, you need to have the relationship defined:
class Ticket extends Model {
protected $table = "tickets";
public function reactions(){
return $this->belongsToMany("App\Reaction");
}
}
And you should have the inverse defined on Reaction:
class Reaction extends Model {
protected $table = "reactions";
public function tickets(){
return $this->belongsToMany("App\Ticket");
}
}
If your models are set-up like so, you shouldn't have any issue attaching the new Reaction to your existing Ticket via your pivot table.
I have the following relations:
Discount:
<?php
class Discount extends Eloquent {
protected $table = 'discount';
public $timestamps = true;
public function title()
{
return $this->hasOne('Translation', 'labelId', 'titleLabelId')->where('languageId', T::getLang())->first()['phrase'];
}
public function titles()
{
return $this->hasMany('Translation', 'labelId', 'titleLabelId');
}
}
?>
Translation:
<?php
class Translation extends Eloquent {
protected $table = 'translations';
public $timestamps = false;
protected $fillable = array('phrase', 'languageId', 'labelId');
public function language()
{
return $this->belongsTo('Language', 'languageId');
}
public function label()
{
return $this->belongsTo('Label', 'labelId');
}
}
?>
Label:
<?php
class Label extends Eloquent {
protected $table = 'label';
public $timestamps = false;
protected $fillable = array('key');
public function translations()
{
return $this->hasMany('Translation', 'labelId', 'id');
}
}
?>
There are three database tables with the following columns:
Discount:
id | titleLabelId
Translation:
id | languageId | labelId
Label:
id
The problem: I'd like to create a title (translation) and associate it with the discount. Here's what I've tried:
$discount = new Discount;
/*create a new label*/
$labelKey = Label::max('key') + 1;
$label = new Label(array('key' => $labelKey));
$label->save();
/*create a new title (and associate it with the label)*/
$title = new Translation(
array(
'phrase' => $input['title'],
'languageId' => 3,
'labelId' => $label->id
));
$title->save();
$discount->save();
$discount->titles()->save($title);
Apparently, the $discount->titles()->save($title); part doesn't work. The title is only attached to the discount if I do it manually: $discount->titleLabelId = $label->id. Is there a way to do it using the ORM?
In your Discount Model, do you have your relationship set up to use the proper table and foreign key?
class Discount extends Eloquent
{
public function titles()
{
return $this->belongsTo('Translation', 'translations', 'titleLabelId');
}
}
When trying to associate one model with another through a defined relationship in Eloquent, you should use the associate() method rather than the save() method.
$discount->titles()->associate($title);
Before this happens though, you should be sure to call the save() method on anything that has been altered or is new.