(laravel4) pulling data from pivot table - laravel

I tried to refrain myself from asking a stupid question once again, but here i am...
So i want to check if a ID in my pivot table (tutorial_id) matches another id. However, i have no idea how to to get this ID from the pivot table.. this is what i tried:
Controller:
class TagController extends BaseController {
public function getTutorials($tag) {
$tag_id = Tag::where('name', $tag)->first();
$tutorials = Tutorial::with('tags')->where('tutorial_id', '=', $tag_id->id)->get();
return View::make('tutorials/tags', array(
'tutorials' => $tutorials
));
}
}
Tutorial model:
class Tutorial extends Eloquent {
protected $table = 'tutorials';
public function tags() {
return $this->belongsToMany('Tag', 'tutorials_tags', 'tutorial_id');
}
}
Tag model:
class Tag extends Eloquent {
protected $table = 'tags';
public function tutorials() {
return $this->belongsToMany('Tutorial', 'tutorials_tags', 'tag_id');
}
}
Database looks like this:
However i now get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'tutorial_id' in 'where clause' (SQL: select * from `tutorials` where `tutorial_id` = 1)

So you want all tutorials with tag_id->id, you can do that like this: $tag_id->tutorials
I reformatted the code for you:
public function getTutorials($tag) {
$tag = Tag::where('name', $tag)->first();
return View::make('tutorials/tags', array(
'tutorials' => $tag->tutorials
));
}
reference: http://vegibit.com/many-to-many-relationships-in-laravel/

Related

Adding and saving fields in a related belongsToMany table

The tables category, category_description and descriptions are related:
public function descriptions(): BelongsToMany
{
return $this->belongsToMany(Description::class);
}
public function categories(): BelongsTo {
return $this->belongsTo(Category::class);
}
public function descriptions(): BelongsTo {
return $this->belongsTo(Description::class);
}
public function descriptions(): BelongsToMany
{
return $this->belongsToMany(Category::class);
}
in Model respectively. When saving or updating:
public function createOrUpdate(Category $category, Request $request)
{
$category->fill($request->get('category'))->save();
$category->descriptions()->syncWithoutDetaching(
$request->input('category.descriptions', [])
);
}
An error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'description' in 'field list' (SQL: insert into `category_description` (`category_id`, `description`, `description_id`, `is_active`, `meta-description`, `meta-h1`, `meta-keyword`, `meta-title`, `name`, `slug`) values (1, 41231231, 0, 1, 23, 124, 12, 12, 12333312, 74))
Perhaps I missed something somewhere, since there is not so much experience.
UPDATE:
a category can have multiple entries, but the description has only one parent. Rewrote — One To Many (Polymorphic):
public function descriptions()
{
return $this->morphMany(Description::class, 'descriptable');
}
public function descriptable()
{
return $this->morphTo();
}
There are no problems with saving 1 record, but how to update several records at the same time?
How about?
// Category Model.
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
public function descriptions()
{
return $this->belongsToMany(Description::class)
->using(CategoryDescription::class);
}
}
// Description Model.
use Illuminate\Database\Eloquent\Model;
class Description extends Model
{
protected $fillable = [
"name",
"description",
"meta-title",
"meta-description",
"meta-keyword",
"meta-h1",
"slug",
"is_active",
];
public function categories()
{
return $this->belongsToMany(Category::class)
->using(CategoryDescription::class);
}
}
// Intermediate Model.
use Illuminate\Database\Eloquent\Relations\Pivot;
class CategoryDescription extends Pivot
{
protected $table = "category_description";
public $incrementing = true;
public function category()
{
return $this->belongsTo(Category::class, "category_id", "id");
}
public function description()
{
return $this->belongsTo(Description::class, "description_id", "id");
}
}
// createOrUpdate method.
public function createOrUpdate(Category $category, Request $request)
{
$category->fill($request->get('category'))->save();
$description = Description::create(
Arr::collapse($request->input('category.descriptions', []))
);
$category->descriptions()->syncWithoutDetaching(
$description->id
);
}
Notes:
Much as this may work for you, I personally think that you don't have a many-to-many relationship here. I believe a one-to-many relationship is sufficient.
The problem is you send data to be inserted in columns that are not found
You should send only the data that you need to insert in the table
so in your case, you should write your function as
$category->descriptions()->syncWithoutDetaching($description_id); // the id of the description you want to attach with this category
If you still don't have the description yet in the database and you are creating it with the same request you can do something like this
Description::create(['columnName'=>$request->get('columnName'),'columnName2'=>$request->get('columnName2')])->id

Laravel eloquent hasManyThrough model access

I have three models as following:
-comments
-item that hasMany comments
-list that hasMany items & hasManyThrough('comment','item)
which means i have lists with many items and items with many comments.the comments are linked to lists via hasManyThrough items.
lists are as follows:
class List extends Model{
protected $fillable = ['title','description','user_id'];
public function items()
{
return $this->hasMany('App\Item');
}
public function comment()
{
return $this->hasManyThrough('App\Comment', 'App\Item');
}}
items:
class Item extends Model
{
//
protected $guarded = [];
protected $fillable = ['title','description','user_id','list_id'];
public function comment(){
return $this->hasMany('App\Comment');
}
public function list(){
return $this->belongsTo('App\List');
}
}
and comments:
class Comment extends Model
{
//
protected $fillable = ['content','item_id','user_id'];
public function items(){
return $this->belongsTo('App\Item');
}
}
How can i access the comments relating to each list?
EDIT: when i try to access the comments for a list with id=15 e.g. $list->comments , i get the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'items.list_id' in 'field list' (SQL: select comments.*, items.list_id as laravel_through_key from comments inner join items on items.id = comments.item_id where items.list_id = 15)

How to fix laravel eloquent many to many relation insertion error on wrong table

I have a model class with the name CourseSession and it's table is course_session, and I have another model named Student and it's table is student and every session has many students and also every student could be in many sessions. So I have created a third table named student_session with student_id, session_id, presence and laravels timestamp columns.
Creating a session needs to have a list of students and I get them from $request like this:
$validatedData = $request->validate([
'students' => 'required',
]);
students is array of students id!
this is my CourseSession model:
class CourseSession extends Model
{
protected $table = 'course_sessions';
protected $guarded = [];
public function course()
{
return $this->belongsTo('App\Course');
}
public function students()
{
return $this->belongsToMany('App\Student', 'student_session','session_id', 'student_id');
}
}
and this is my student model:
class Student extends Model
{
protected $guarded = [];
public function courses()
{
return $this->belongsToMany('App\Course');
}
public function exams()
{
return $this->belongsToMany('App\Exam');
}
public function sessions()
{
return $this->belongsToMany('App\CourseSession', 'student_session', 'student_id', 'session_id');
}
}
I create a session like this:
$session = new CourseSession();
$session->course_id = $course->id;
$session->save();
and I save students this way:
$sessions = $session->students()->create(['session_id' => $session->id, 'student_id' => 1, 'presence' => 1]);
but I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'session_id' in 'field list' (SQL: insert into `students` (`session_id`, `student_id`, `presence`, `updated_at`, `created_at`) values (25, 1, 1, 2019-04-28 14:24:48, 2019-04-28 14:24:48))
according to error, it tries to write data on students table but I want to write them on student_session table!
what is wrong in my codes?
For this you want to use attach() instead of create().
$session->students()->attach(1, ['presence' => 1]);
In the above example 1 is the student_id. You don't need to specify the session_id as your calling this from a Session model. The array at the end is any additional data you want to add to the pivot table.
Since you have additional data in your student_session pivot table, it might also be an idea to add this to your belongsToMany relationships e.g.
public function sessions()
{
return $this->belongsToMany('App\CourseSession', 'student_session', 'student_id', 'session_id')
->withPivot('presence')
->withTimestamps();
}
This will include the presence and timestamps columns in the pivot data as well (obviously, you don't have to do this if you don't want to though).

Sort eloquent model with eager loaded relationship in Laravel

I'm trying to build a small application where I am having three models, I want to sort the model by column inside the eager load relationship, for this I have a model named AssociatedCompany as:
class AssociateCompany extends Model {
protected $table = 'project_associate_company';
protected $fillable = [
'project_id', 'company_role_id', 'company_specialisation_id', 'company_id', 'link', 'file_name'
];
public function project()
{
return $this->belongsTo('App\Project','project_id','id');
}
public function companyRole()
{
return $this->belongsTo('App\Role', 'company_role_id','id');
}
}
and other model Role as :
class Role extends Model
{
protected $table='company_role';
protected $fillable = [
'sl', 'name', 'parent_id'
];
}
Now I want to fetch all the companies of related project and sort them out with sl of role, for this I am trying to do a join something like this:
$companies = Project\AssociateCompany::whereHas('project', function ($q) use($request) {
$q->where('slug', $request->slug);
})
->with('companyRole')
->join('company_role', 'project_associate_company.id', '=', 'company_role.project_associate_company_id')
->orderBy('company_role.sl', 'desc')
->paginate(20);
So in this I am getting an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company_role.project_associate_company_id' in 'on clause' (SQL: select count(*) as aggregate from project_associate_company inner join company_role on project_associate_company.id = company_role.project_associate_company_id where exists (select * from projects where project_associate_company.project_id = projects.id and slug = kovacek-rodriguez and projects.deleted_at is null) and project_associate_company.deleted_at is null)
Help me out in this.

SQLSTATE[42S22]: Column not found: 1054 Unknown column created_at and updated_at column missing

I'm encountering error like SQLSTATE[42S22]: Column not found: 1054 Unknown column 'updated_at' in 'field list' (SQL: insert into buildings (building_name, updated_at, created_at) values (Building Four, 2017-10-12 02:56:13, 2017-10-12 02:56:13)). but i don't have a updated_at and created_at column in my database how come these columns shows up in the error?
BuildingRepository.php
<?php
namespace App\Repositories\Building;
use App\Building;
interface BuildingRepository
{
public function getById($id);
public function getAll();
public function create(array $attributes);
public function update($id, array $attributes);
public function delete($id);
}
EloquentBuilding.php
<?php
namespace App\Repositories\Building;
use \App\Building;
class EloquentBuilding implements BuildingRepository
{
private $model;
public function __construct(Building $model)
{
$this->model = $model;
}
public function getById($id)
{
return $this->model->findOrFail($id);
}
public function getAll()
{
return $this->model->all();
}
public function create(array $attributes)
{
return $this->model->fill($attributes)->save();
}
public function update($id, array $attributes)
{
}
public function delete($id)
{
}
}
BuildingController.php
<?php
namespace App\Http\Controllers;
use App\Building;
use Illuminate\Http\Request;
use App\Repositories\Building\BuildingRepository;
class BuildingController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
private $building;
public function __construct(BuildingRepository $building)
{
$this->building = $building;
}
public function createBuilding()
{
return view('building.create');
}
public function store(Request $request)
{
$this->validate($request, array(
'building_name'=>'required',
'building_information'=>'required',
));
$buildings = array('building_name' => $request->building_name,
'building_inforamtion' => $request->building_information);
$this->building->create($buildings);
}
public function getAllBuilding()
{
$buildings = $this->building->getAll();
return view('building.show')->with('buildings', $buildings);
}
public function getSpecificRecord()
{
$buildings = $this->building->getById(1);
return view('building.show')->with('buildings', $buildings);
}
}
Building.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
protected $fillable = [
'id', 'building_name', 'building_information', 'building_image',
];
}
By default, Eloquent expects created_at and updated_at columns to exist in your tables. If you do not wish to have these columns to be automatically managed by Eloquent, then you need to set the $timestamps property in your model to false. Your file Building.php should look like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Building extends Model
{
public $timestamps = false;
protected $fillable = [
'id', 'building_name', 'building_information', 'building_image',
];
}
Yes, by default Eloquent expects created_at & updated_at columns in all your tables. You can set $timestamps property to false.
To make a column nullable, you mention that in your migration. For example, I want to make address column of my table nullable, I do this.
$table->string('address')->nullable();
I faced the same issue.
The problem was that the column name that I mentioned inside migration was not same as what I was using inside my controller, model and view.
So, I would suggest that you check whether you have taken same column name inside the migration that you are further using for mass assignment.
Turn places created_at and updated_at from the database

Resources