As you can see on the following image my laravel relation between shoporder and shoporderroutingstepplans is not as it has to be.
I have no idea what I exactly did wrong so I hope someone can help me out. In the code beneath I have left some fields out of the code to make it more legible.
class shoporder extends Model
{
protected $primaryKey = 'ID';
protected $fillable = [
'CADDrawingURL',
'ID',
'Costcenter',
'CostcenterDescription',
'Costunit',
'CostunitDescription',
'Created',
'Creator',
'CreatorFullName',
'Description',
'ShopOrderParent',
'ShopOrderParentNumber',
'ShopOrderRoutingStepPlanCount',
'Status',
'SubShopOrderCount',
];
public function shopOrderRoutingStepPlans() {
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
}
}
class ShopOrderRoutingStepPlan extends Model
{
protected $primaryKey = 'ID';
public $table = "shoporderroutingstepplans";
protected $fillable = [
'Account',
'ID',
'AccountName',
'AccountNumber',
'AttendedPercentage',
'Backflush',
'Created',
'Creator',
'CreatorFullName',
'Description',
'ShopOrder',
];
public function shopOrder() {
return $this->belongsTo('App\shopOrder', 'ShopOrder', 'ID');
}
}
This is the code Im executing to get the relations of 1 shoporder in the controller.
$orders = shopOrder::find('0600959e-6b92-4135-8ea8-1fa2fd92a916')->shopOrderRoutingStepPlans()->get();
In the shoporder migration I defined the primary key:
$table->string('ID')->unique();
$table->primary('ID');
In the shoporderroutingstepplans migration I defined the foreign key as followed.
$table->string('ID')->unique();
$table->primary('ID');
$table->foreign('ShopOrder')
->references('ID')
->on('shoporders');
You must switch the order of the last two parameters:
From
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
To
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ID', 'ShopOrder');
The parameters are
model,
name of column in the linked model,
name of column in this model.
Related
Hey there stackoverflow
I am currently building a course application as part of my laravel project.
My problem lies in how the eloquent handle model relations, i'm still kinda new to eloquent, so hopefully you can answer my question.
The structure
The Course has many episodes and each episode has many sections.
Which means I have 3 tables in the DB. Courses -> course_episodes -> course_episode_sections
ID table is where i connect courses with users - course_users.
Right now i can create courses and and put in all the data correctly.
The Problem
I need to retrieve all the courses and its nested children that the user has bought, which is connected in the course_users table with columns course_id and user_id
Course structure
Same stucture in DB
course: {
name: null,
sub_title: null,
estimate: null,
trailer: null,
type: null,
text: null,
course_episodes: [
{
name: null,
section: [
{
order: null,
type: null,
content: null,
},
]
},
]
}
Model Pictures
My models as of right now.
class CourseUsers extends Model {
protected $fillable = [
'id',
'course_id',
'user_id',
'active',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courses()
{
return $this->belongsToMany(Course::class);
}
public function user(){
return $this->belongsTo(User::class);
}
public function scopeFindForUserId($query, $userId)
{
return $query->where(function ($q) use ($userId) {
$q->where(function ($q) use ($userId) {
$q->where('user_id', $userId);
});
});
}
Course model
class Course extends Model{
protected $fillable = [
'id',
'name',
'sub_title',
'type',
'estimate',
'trailer',
'gateway_id',
'text',
'active',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courseEpisode()
{
return $this->hasMany(CourseEpisode::class);
}
public function courseUsers() {
return $this->hasMany(CourseUsers::class);
}
public function scopeActive(Builder $builder)
{
return $builder->where('active', true);
}
Course episode Model
class CourseEpisode extends Model implements HasMedia {
use HasMediaTrait;
protected $fillable = [
'id',
'course_id',
'order',
'name',
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function course()
{
return $this->belongsTo(Course::class);
}
public function courseSection()
{
return $this->hasMany(CourseEpisodeSection::class);
}
Course episode sections
class CourseEpisodeSection extends Model {
protected $fillable = [
'id',
'course_episode_id',
'order',
'type',
'content'
];
protected $hidden = [
'deleted_at',
'updated_at',
'deleted_at'
];
public function courseEpisode()
{
return $this->belongsTo(CourseEpisode::class);
}
According to your explanation, course_users table holds many-to-many relationship between Course and User model. In case of a many-to-many relationship, you actually don't need a CourseUser model. This kind of table which holds many-to-many relationship is called pivot table. Read more from the Official Documentation
I am defining only the relationships with your Course, User, CourseEpisode, CourseEpisodeSection models.
Course.php
class Course extends Model
{
public function courseEpisodes()
{
return $this->hasMany(CourseEpisode::class);
}
public function users()
{
return $this->belongsToMany(User::class,'course_users')->withPivot('active');
}
}
CourseEpisode.php
class CourseEpisode extends Model
{
public function courseSections()
{
return $this->hasMany(CourseSection::class);
}
}
User.php
class User
{
public function courses()
{
return $this->belongsToMany(Course::class,'course_users')->withPivot('active');
}
}
If you want to get all the children relationships from a user, use nested eager loading :
$user_with_nested_course_data = User::with('courses.courseEpisodes.courseSections')->find($id);
I have two models:
Team
Game (Played between two games)
The Game model has two foreign keys pointing to the Team model - team1_id & team2_id.
Here's the code for Team model:
class Team extends Eloquent
{
protected $table = 'team';
protected $fillable = [
'name',
'color',
'year'
];
public function games()
{
return $this->hasMany(\App\Models\Game::class);
}
}
Code for Game model:
class Game extends Eloquent
{
protected $table = 'game';
protected $casts = [
'team1_id' => 'int',
'team2_id' => 'int'
];
protected $fillable = [
'team1_id',
'team2_id',
'location',
'start_at'
];
public function team1()
{
return $this->hasOne(\App\Models\Team::class, 'team1_id');
}
public function team2()
{
return $this->hasOne(\App\Models\Team::class, 'team2_id');
}
}
I get an error saying the column could not be found.
return $this->hasMany(\App\Models\Game::class, 'team1_id');
This works, but the problem is that I want to get games depending on both team1_id and team2_id.
You had to specify the foreign key and the local key you use to reference that relation
public function localTeam()
{
return $this->belongsTo(\App\Models\Team::class, 'id', 'team1_id');
}
public function foreignTeam()
{
return $this->belongsTo(\App\Models\Team::class, 'id', 'team2_id');
}
TL;DR
Trying to get three models to interact using eloquent for a rest api.
User - belongsToMany(pulls)
Pull - belongsToMany(user) && belongsToMany(boxes)
Box - belongsToMany(pulls)
The pull_user table is working perfectly, I can just attach a user after I save a pull. Saving a box works fine but the attach doesn't work/enter anything into the pivot table (I get no errors though).
The Problem
I can't get a pivot table that associates two of my models together to attach() after a save. I have the three models listed above, the pivot is working for pull_user but not for pull_box even though the save for box is working perfectly. I am able to save a box without an error but the association just never occurs (no error).
The Code
pull_box.php
class PullBox extends Migration
{
public function up()
{
Schema::create('pull_box', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('pull_id');
$table->integer('box_id');
});
}
public function down()
{
Schema::dropIfExists('pull_box');
}
}
Pull.php
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box');
}
}
Box.php
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull');
}
}
BoxController.php
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
...
]);
$user_id = $request->input('user_id');
...
$box = new Box([
'user_id' => $user_id,
...
]);
$pull = Pull::whereId($pull_id)->first();
if($box->save()){
$pull->boxes()->attach($box->id);
$box->view_box = [
'href' => 'api/v1/box/' . $box->id,
'method' => 'GET'
];
$message = [
'msg' => 'Box created',
'box' => $box,
'pull' => $pull_id
];
return response()->json($message, 201);
}
$response = [
'msg' => 'Box creation error, contact supervisor',
];
return response()->json($response, 404);
}
The Solution
I need to know how I can get this association working. I am going to need to add a new layer in under the pull for Item, but I don't want to move one before I solve this. I think that my problem has to stem from a syntactical/logical error on my part but I can't see it. There are a bunch of questions on SO that are very close to giving me a solution, but after reading them I wasn't able to solve my problem.
Any help is appreciated.
Try renaming your pull_box table to box_pull, pivot tables on laravel must be in alphabetical order. If you want to use custom name on pivot table you have to extends your pivot, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PullBox extends Pivot
{
protected $table = 'pull_box';
}
And your many to many relationships:
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box')->using('App\PullBox');
}
}
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull')->using('App\PullBox');
}
}
i made third table because i need extra colums in third table.
i has written relation method in both model but id is not
moving
in user model method is
class User extends Model
{
protected $fillable = [
'user_type_id', 'accountType', 'email', 'password', 'userName', 'gender', 'dob', 'country', 'city', 'mobileNo', 'cnic', 'address',
'degreeLevel', 'degreeTitle', 'institution', 'complitionYear', 'acedCountry', 'experience', 'workExperience', 'industry', 'perCountry', 'cv'
];
protected $table = 'users';
/********************************************************************/
/* Relationship between User and Ranklist */
/*******************************************************************/
public function RankList()
{
return $this->hasMany('App\Models\RankList','user_id');
}
public function Company()
{
return $this->hasMany('App\Models\Company');
}
public function newsAndEvents()
{
return $this->hasMany('App\Models\newsAndEvents','user_id');
}
/********************************************************************/
/* Relationship between User and user type */
/*******************************************************************/
public function UserType()
{
return $this->belongsTo('App\Models\UserType','user_type_id');
}
public function course_outline()
{
return $this->belongsTo('App\Models\CourseOuline','user_id');
}
public function Jobs()
{
return $this->belongsToMany('App\Models\Job','Job_User','User_id','Job_id');
}
public function Skill_User()
{
return $this->belongsToMany('App\Models\Skill','Skill_User','Skill_id','User_id');
}
public function Feedback_User()
{
return $this->belongsToMany('App\Models\Feedback','Feedback_User','Feedback_id','User_id');
}
}
in job model method is
class Job extends Model
{
use SoftDeletes;
protected $dates = ['deleted_at'];
/**************************************************/
/* Company Post Job */
/**************************************************/
protected $fillable = [
'jobType', 'jobTitle','skills','industry', 'department', 'vacancy', 'qualification', 'degreeTitle', 'miniExperience', 'jobCategory',
'city', 'gender', 'companyName', 'description','posting_date', 'applied_date', 'companyLogo',
];
protected $table = 'jobs';
/**************************************************/
/* Relationships between company and job */
/**************************************************/
public function Company()
{
return $this->belongsTo('App\Models\Company','company_id');
}
public function job_skill()
{
return $this->belongsToMany('App\Models\Skill','Job_Skill','Job_id','skill_id');
}
public function Users()
{
return $this->belongsToMany('App\Models\User','Job_User','User_id','Job_id');
}
}
pivot table code is
class Job_User extends Model
{
protected $fillable = [
'cv','current_salary','expected_salary','status',
];
protected $table = 'jobs_users';
}
but user apply on job error is shown
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (bridging_the_gap.jobs_users, CONSTRAINT jobs_users_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE ON UPDATE CASCADE) (SQL: insert into jobs_users (cv, current_salary, expected_salary, updated_at, created_at) values (1st, 15,000-19,999, 30,000-39,999, 2016-06-02 10:57:02, 2016-06-02 10:57:02))
Try something like this
//model jobs
public function Jobs()
{
return $this->belongsToMany('App\Models\jobs_users');
}
//model users
public function Users()
{
return $this->belongsToMany('App\Models\jobs_users');
}
//model pivot - jobs_users
public function user() {
return $this->belongsTo('App\Models\user');
}
public function jobs() {
return $this->belongsTo('App\Models\job');
}
This are basics to make pivot (many to many relation). For more fields you have to define in pivot model extra fields etc...
Hope it helps
Can you help me with this one?
ANSWER MODEL
class Answer extends Eloquent {
protected $primaryKey = 'ID';
protected $table = 'answers';
protected $fillable = array('customerID', 'agentID', 'status', 'date', 'urn_code', 'urn_id');
public function customer(){
return $this->hasOne('Customer');
}
}
CUSTOMER MODEL
class Customer extends Eloquent {
protected $connection = 'mysql';
protected $table = 'leads';
protected $primaryKey = 'cID';
protected $fillable = array('cID','title', 'first_name','last_name','address1', 'address2', 'post_code','city','phone_number');
public function answers() {
return $this->hasMany('Answer');
}
}
ROUTE
Route::get('sales', function(){
$sales = Customer::with('answers')->get()->paginate(15);
foreach($sales as $sale)
echo $sale->last_name . '<br />';
});
and this is my error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'answers.customer_id'
It's exactly how the error says. In your answers table, Laravel is looking for a customer_id column automatically, and it doesn't exist in this case.
If your customer ID column is under a different name, you can specify it as the second parameter in the hasMany() method:
public function answers() {
return $this->hasMany('Answer', 'my_column');
}
Also, you should probably be using a belongsTo relationship here, as pointed out by #razor.
Since you are using custom primary keys, you need to specify the local key and the foreign key.
public function answers() {
return $this->hasMany('Answer', 'foreign_key', 'local_key');
}
Probably you'll have to update your Answer model as well (please, check out if you really need a hasOne or a belongsTo relation):
public function customer(){
return $this->belongsTo('Customer', 'foreign_key', 'local_key');
}
You can find more info here.