I have create two tables
AREAS
-id
-areaName
SOCIETIES
-id
-area_id
-societyName
My relationship is defined like this
class Area extends Model
{
//
public function society()
{
return $this->hasMany('App\Society');
}
}
class Society extends Model
{
public function area()
{
return $this->belongsTo('App\Area');
}
}
Now I have created objects for both area and society
$area = new \App\Area();
$area->areaName = $input['areaName'];
$society = new \App\Society();
$society->societyName = $input['societyName'];
$society->area()->associate($area);
After this when I call "$society->save()" its not saving any record and giving error area_id cannot be null. I want to save society and its relation area in one go.
When I use "$area->save()" before associate its saving the record when calling "$society->save()". All I want to do is skip "$area->save()" and save both society and area in one go.
It is giving you the error because you don't have a record in the database with an id for it. You need to save the area record first and then associate it with the relation. I don't think it will work other wise, take a look at eloquent docs on laravel's website:
https://laravel.com/docs/5.1/eloquent-relationships
Related
I am using Laravel 5's belongsToMany method to define related tables using an intermediary pivot table. My application is using the eloquent models Tour and TourCategory. In the Tour Model I have:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tour extends Model
{
public function cats(){
return $this->belongsToMany('App\TourCategory', 'tour_cat_assignments', 'tour_id', 'cat_id');
}
}
In my controller I am retrieving all the data from the tour table along with the associated category data using Laravel's with method:
$tours = Tour::with('cats')->get();
That all works fine. The problem is that I don't want the category data in its current raw form, I need to first rearrange it. However I cannot overwrite the cats property without unsetting it first:
public function serveTourData(){
$tours = Tour::with('sections', 'cats')->get();
foreach($tours as $tour){
unset($tour->cats); // If I unset first, then it respects the new value. Why do I need to do this?
$tour->cats = "SOME NEW VALUE";
}
Log::info($tours);
}
Can someone explain the logic behind this please?
To override relations on some model, you can use:
public function serveTourData(){
$tours = Tour::with('sections', 'cats')->get();
foreach($tours as $tour){
$tour->setRelation('cats', "SOME NEW VALUE");
}
Log::info($tours);
}
For laravel 5.4 - setRelation
Of course if you are using laravel >= 5.6, you can unset relations by unsetRelation
I have the followings tables:
tbl_project(id, description)
tbl_operation(id, project_id, name)
tbl_itemType(id, operation_id, name)
tbl_item(id, itemType_id, name, unit, price)
I wanna when i create a new project, it adds some operations in tbl_operation and then adds some itemTypes to tbl_itemType and then adds some items in tbl_item. How can i do it in afterSave() behavior of project's model?
I read the following link, but i don't know is it possible to do by this?
esaverelatedbehavior
just create a function in your ProjectModel
public function afterSave()
{
$operation_model = new Operation();
$operation_model->setAttributes($YOUR_DATA);
$operation_model->save(); // create your operation
// same goes for every other data you want to save
return parent::afterSave(); // keep the chain
}
You could make use of the relations. This approach will only work if the respective relation contains only the models to be saved. In your controller have
$project->operations = array(/*your operations*/);
In turn each operation model could also have the related itemTypes
$operation->itemTypes = array(/*itemTypes for this operation*/)
And lastly each itemType could have the related items.
And in your afterSave for operations have
public function afterSave() {
foreach ($this->operation as $op) {
$op->project_id = $model->id;
$op->save();
}
return parent::afterSave();
}
For the afterSave for the Operation and ItemType classes should in turn save the related ItemTypes and Items respectively.
Better use afterSave() function , i think it will work for you
I have many-to-many relation between two models: movie and actor.
I need to obtain relation ID after saving it, to use it later. Here's the code:
$movie->actors()->save($actor); // it saves my relation
$relationID = 'how to obtain ID of new record in pivot table?';
I did it this way:
In Movie model:
public function actors()
{
return $this->belongsToMany('Actor')
->withPivot('id');
}
And I obtained ID this way:
$relationID = $movie->actors()
->where('actor.id', $actor->id)
->first()->pivot->id;
Ugly, but works. If it can be done any better, please let me know. :)
I'm fairly new with Laravel. I'm still trying to learn it. My question is:
I have 3 tables named
games
game_options
game_platforms
I have 3 Models for those tables
Game Model
class Game extends Eloquent
{
protected $table = 'games';
public function platforms()
{
return $this->hasManyThrough('GamePlatform','GameOptions','id','game_id');
}
}
GamePlatform Model
class GamePlatform extends Eloquent
{
protected $table = 'game_platform';
}
GameOption Model
class GameOptions extends Eloquent
{
protected $table = 'game_options';
}
So when I do
$game = Game::find(1)->platforms;
It only shows,
{"id":1,"platform_id":20,"game_id":1}
{"id":1,"platform_id":21,"game_id":1}
{"id":1,"platform_id":22,"game_id":1}
{"id":1,"platform_id":23,"game_id":1}
{"id":1,"platform_id":24,"game_id":1}
But I need game name and platform names with those ID's. The thing is, I want to do this with eloquent only. I could go with "DB" or oldschool SQL but I want to learn if this way is possible or not.
Also I'm looking for better documentation/books for laravel. Most of what I read were only introduce laravel or far too advanced for me.
I left a comment earlier about this but now I'm pretty sure it's the answer you're looking for: you should use belongsToMany rather than hasManyThrough. So first, might I suggest you rename your tables and models to follow Laravel's conventions (plural snake_case table names, singular snake_case alphabetical order pivot table names, singular StudlyCaps model names), that way you'll have the following situation:
Tables:
games
id
name
game_option
id
game_id
option_id
options
id
option
name
Now you can rewrite your models to conform to the new structure, and use a belongsToMany relationship too:
class Game extends Eloquent
{
public function platforms()
{
return $this->belongsToMany('Option');
}
}
class Option extends Eloquent
{
public function platforms()
{
return $this->belongsToMany('Game');
}
}
Note: you don't have to model the pivot table (game_option) unless you store extra data on the pivot.
Now you should be good to get all options for a given game:
$options = Game::find(1)->options;
Or if you need to get all platforms (though I am trying to infer meaning of your code here regarding options and platforms):
$platforms = Game::find(1)->options()->whereOption('platform')->get();
you can use the with method with eloquent
$game = Game::where('id',1)->with('platforms')->get();
Should return you the game and platforms
For documentation I would first start with the documentation provided (find it to be about 50% complete) and with the api everything else is covered
You would have to model your tables like:
**games**
id
name
**game_options**
id
game_id
name
**game_platform**
id
game_options_id
platform_id /* which i assume you get from a platform master table */
Then in your Game Class:
class Game extends Eloquent
{
protected $table = 'games';
public function platforms()
{
return $this->hasManyThrough('GamePlatform','GameOptions','game_id','game_options_id');
}
}
Now, this would be assuming that Game Platform belongs to Games through Game Options.
I have three table company,group and company_group.
I am getting values from post while saving a company.
In my company form i have multiple select box which has a list of group.
My company is getting saved correct-ally but now i want to add record in company_group table with last inserted id of company and selected group.
I have set up has_many in both models company and group but cannot save multiple records in company_group table so help me with this.
Company model
class Company extends DataMapper {
var $has_one=array("group");
function __construct() {
parent::DataMapper();
}
}
group model
class Group extends DataMapper {
var $has_many=array("company");
function __construct() {
parent::DataMapper();
}
}
company controller
class Company_c extends CI_Controller {
public function index() {
$company = new company();
$group=new group();
$company->id=1;
$group->id=2;
$group->id=4;
$company->save($group);
}
}
Please help me with this
You're not loading the company or group objects properly. When you instantiate a company, you need to do:
$company = new Company();
$company->where('id', 1)->get();
or, quicker as a shorthand (as long as you use the id property):
$company = new Company(1);
(Note that the class name is case-sensitive).
You then do the same with the group(s) you want to load:
$groups = new Group();
$groups->where_in('id', array(2, 4)->get();
Then, when both are instantiated, you can save the company and its group(s) in one go:
$company->save($groups);
Make sure you go through the DataMapper docs thoroughly, it couldn't really be explained more clearly:
http://datamapper.wanwizard.eu/pages/save.html#Relationship