Laravel hasManyThrough Eloquent query failing - laravel

I have 3 models:
Client, Store, Format
A client has many stores, and a store has one format.
So, I would like to get all Formats from Client.
In Store table, I have client_id, format_id
in Format table, I have no direct relationship, I have plan_id
In Plan table, I have client_id.
In Client table, I have no useful relationship
I need to get all formats of a client,
So I need to create a relationship $client->formats
So basically,I want to do a hasManyThrough relationship,
class Client extends Model {
protected $table = 'client';
protected $primaryKey = 'clientid';
public function formats()
{
return $this->hasManyThrough(Format::class,Store::class, 'clientid', 'storeid');
}
}
But I get this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'format.storeid' in 'on clause' (SQL: select `format`.*, `store`.`clientid` from `format` inner join `store` on `store`.`storeid` = `format`.`storeid` where `store`.`clientid` = 58)
I'm a little bit stuck in this relation, any idea how to fix it????

You have a many-to-many relationship
class Client extends Model {
protected $table = 'client';
protected $primaryKey = 'clientid';
public function formats()
{
return $this->belongsToMany(Format::class, 'Store_table', 'client_id', 'format_id');
}
}

Related

Create eloquent relationships for Table with foreign keys to Pivot table - Laravel

I have a pivot table (builder_project) which I'm using on a many-to-many relationship between the 'projects' and 'builders' tables. And everything is working fine to this point.
However, I would like users to be able to add 'notes' to the pivot table (builder_project) and because many notes should be able to be added I created a table called 'notes' which has a one-to-many relationship with the pivot table.
I tried creating a model for the pivot table, however; when I try to access the method within the pivot model, I'm getting the following error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'notes.' in
'where clause' (SQL: select * from builder_project where exists
(select * from notes where builder_project.project_projectID =
notes.``))
This is the code for my pivot model:
namespace Estimating;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Builder_project extends Pivot
{
protected $table = "builder_project";
protected $primaryKey = 'project_projectID'; // I need to add the other primary key here but I undestand it's not possible on Laravel
protected $fillable = [
'project_projectID',
'builder_builderID',
'note',
];
// One to many relationships
/**
*
*/
public function test()
{
return $this->hasMany('Estimating\Builder_project_note');
}
}
This is the model for Builder_project_note:
<?php
namespace Estimating;
use Illuminate\Database\Eloquent\Model;
class Builder_project_note extends Model
{
//Determines which database table to use, in this case 'projects' table
protected $table = "notes";
protected $primaryKey = 'noteID';
protected $fillable = [
'project_projectID',
'builder_builderID',
'note',
];
// One to many relationships
/**
* Get the status that owns the project.
*/
public function test()
{
return $this->belongsTo(
'Estimating\Builder_project'); // I know that here I need an ID from Builder_project pivot table - but I have a composite key!;
}
}
And this is how I'm trying to get the data from my controller and I get the error:
public function editBuilderProject(Request $request, $builderID, $projectID)
{
$browserDetails = new Agent();
$project = Project::find($projectID);
$builder = Builder::find($builderID);
$builder_project_statuses = Builder_project_status::all();
$builder_project_note = Builder_project::has('test')->get();
dd($builder_project_note);
return view('projects/edit-builder-project', compact('browserDetails', 'project','builder', 'builder_project_statuses', 'builder_project_note'));
//return $projectID." ". $builderID;
}
I would appreciate if anyone can point me to the right direction with this and my apologies if I'm not being clear enough - this is my first post here :)
I've uploaded a sample of my database model:
Database Model example
Laravel does not like primary keys based upon multiple columns. You need to add its own builder_project.id column (in your pivot table) which will be the field used by your notes table.

laravel Eloquent ORM custom field name

I am trying to get record from a products table with the field productsid by using Eloquent and using the following code. My model name is Products_description.
In my route file.
Route::get('product/{productsid}','productscontroller#show');
In my controller file
public function show($productid)
{
$Products = Products_description::find($productid);
return $Products;
}
But it showing me the error that Unknown column 'products_description.id'. Looks like Eloquent try to get record through the field name id by default like it do with the table names. But how to get records through a table field other than id. e.g. if it is productid, what we would do/use?
In your model, declare your $primaryKey
class Products_description {
protected $primaryKey = "productid";
//
}
This way you can use ::find or firstOrFail and not where.
like this
$Products = Products_description::where('pruductid',$productid)->first();
or you can try this
Products_description model
class Products_description extends Eloquent {
protected $primaryKey = 'productid';
}
I am assuming your need is to query your table for a field other than the primary key . You can use:
Products_description::where('productid',$productId)->first()
If you are speaking about foreign keys, then you should define them in the model like so :
return $this->hasOne('App\Phone', 'foreign_key');
Here is the relevant documentation :
https://laravel.com/docs/5.1/eloquent-relationships#one-to-one

Laravel 5. How to create a register using tables : users,profile and account

i'm trying to create a system of register and authentication using three tables. Users, Account and Profile.
But when attempting to use a registration form displays the following message below:Tables
Column not found: 1054 Unknown column 'email' in 'where clause' (SQL: select * from users where email = thiagothgb#gmail.com limit 1)
I do a relationship in the models Users like that.
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
use App\Model\Account;
use App\Model\Profile;
class Users extends Model
{
protected $table = 'users';
protected $connection = 'mysql';
public function account(){
return $this->hasOne('App\Model\Account');
}
public function profile(){
return $this->hasOne('App\Model\Profile');
}
}
What I can try to for to solve this problem and extend Models when i go create a object extended.

Cannot access Collection::$items

I've got some troubles with an eloquent query.
Users have many feeds and feeds have many items.
I need to get all the items that belongs to the feeds of the user order by date.
I've got a pivot table:
feed_user
----------
- id
- feed_id
- user_id
and relationships are defined like this in my models:
class UsersController extends BaseController {
public function feeds() {
return $this->hasMany('feed');
}
class Feed extends \Eloquent {
protected $fillable = [];
public function users() {
return $this->belongsToMany('User');
}
public function items() {
return $this->hasMany('Item');
}
class Item extends \Eloquent {
protected $fillable = [];
public function feed() {
return $this->belongsTo('Feed');
}
But when I do this query...
Auth::user()->feeds->items->orderBy('date', 'DESC')->get();
It returns this error:
Cannot access protected property Illuminate\Database\Eloquent\Collection::$items
There are a couple issues here.
First, the relationship on User model is not correct. A hasMany relationship is one half a one-to-many relationship. This would assume that a feed belongs to one user, and that the feed table has the user_id field. A many-to-many relationship is defined by adding a belongsToMany relationship on both models. So, a user belongsToMany feeds, and a feed belongsToMany users.
class User extends \Eloquent {
public function feeds() {
return $this->belongsToMany('feed');
}
}
Next, the error you're seeing is because Auth::user()->feeds returns a Illuminate\Database\Eloquent\Collection object. You're then trying to access the items attribute on the Collection, which is protected and throws the error you're seeing.
Finally, since Laravel does not use joins for relationships, you cannot order a query by a field on a related table without manually doing the join yourself.
Try using eager loading:
Auth::user()->with('feeds.items')->orderBy('date', 'DESC')->get();

working with m:m relationships in eloquent outside laravel

I have been able to set up a m:m relationship in eloquent outside laravel and retrieve records but I have no idea how to add a new record as you dont create the pivot table in the code.
If these are my classes, how would i add a new instance to the M:M relationship between author and publisher?
<?php
include 'eloquent_database.php';
class Publisher extends Illuminate\Database\Eloquent\Model {
public $timestamps = false;
protected $table = 'publisher';
protected $primaryKey = 'publisher_id';
public function authors (){
return $this->belongsToMany('Author', 'author_publisher', 'publisher_id', 'author_id');
}
}
class Book extends Illuminate\Database\Eloquent\Model {
public $timestamps = false;
protected $table = 'book';
protected $primaryKey = 'book_id';
public function author() {
//related table name, pk in current table,
return $this->belongsTo('Author', 'author_id');
}
}
// Create the company model
class Author extends Illuminate\Database\Eloquent\Model {
public $timestamps = false;
protected $table = 'author';
protected $primaryKey = 'author_id';
public function books()
{
//related table, fk IN related table,
return $this->hasMany('Book', 'author_id');
}
public function publishers (){
return $this->belongsToMany('Publisher', 'author_publisher', 'author_id', 'publisher_id');
}
}
I would also need to know how to delete one too. I have seen this documentation http://laravel.com/docs/4.2/eloquent#working-with-pivot-tables but i dont really follow it
Id really appreicate an exxample of how to add and delete a new instance. Also onine there seeems to be so many different versions its hard to find which docs to follow as the code i have works but i didnt get it from the docs - just trial and error
Thanks a lot in advance
edit:
in repsonse to Rays comment i do have a pivot table in the database called author_publisher with author id and publisher id but i have no idea how to work with this pivot table. Do i have to create a class for it? I dont really understand
Here is a reference to said table in the code above
return $this->belongsToMany('Author', 'author_publisher', 'publisher_id', 'author_id');
When having a M:M relationship, make sure you have a table that translates the relationship between author and publisher. An example table could be composed of entries including both author_id and publisher_id. From what you have provided, you lack such a table.
There's another case if you do not have such a table. In order for such a M:M relationship to work, the author table must contain a column called "publisher_id" for simplicity. Likewise the publisher table must contain a column called "author_id". Then in the author model, return $this->hasMany('Publisher', 'author_id') and in the publisher model, return $this->hasMany('Author', 'publisher_id'). You should get the correct answer.

Resources