cannot get the relationship data in laravel - mysql

this is my function
public function show($id)
{
$newproject = Newproject::find($id);
$data = [
'name' => $newproject->user->name
];
return $data;
}
newproject model
public function user()
{
return $this->hasOne(User::class,'user_id' ,'id');
}
it always getting the error
message: "SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.user_id' in 'where clause' (SQL: select * from `users` where `users`.`user_id` = 1 and `users`.`user_id` is not null limit 1)"
exception: "Illuminate\Database\QueryException"
file: "C:\xampp\htdocs\larastart\vendor\laravel\framework\src\Illuminate\Database\Connection.php"
line: 669
please help my to solve my problem please.

Check the relationship one-to-one reference
The foreign_key user_id is in newprojects table, you need to build the relationship like this:
User model:
public function newproject()
{
return $this->hasOne(Newproject::class,'user_id');
}
newproject model:
public function user()
{
return $this->belongsTo(User::class);
}

I think it should be something like this,
public function user()
{
return $this->hasOne(User::class,'id' ,'user_id');
}
It means id of users table match with current model's user_id column. And if you have proper naming convention according to laravel then you don't need to pass this extra params.
Laravel hasOne relation
Hope it helps:)

found the problem in my model
in user model
public function newproject()
{
return $this->belongsTo(Newproject::class,'user_id','id');
}
in newproject model
public function user()
{
return $this->hasOne(User::class,'id' , 'user_id');
}
thanks all

Related

many-to-many relationship: order by on pivot table not working

I have these relationship between school and associate models:
// School model
public function associates()
{
return $this->belongsToMany('Associate', 'school_associate', 'school_id', 'associate_id')
->withPivot('start_date', 'end_date');
}
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date');
}
I need to get all associates of one school ordered by start_date.
This is what I tried without success (in this try I am searching in all schools):
dd(\App\Associate::with(['schools' => function ($q) {
$q->orderBy('pivot_start_date', 'desc');
}])->toSql());
And I get this sql (notice no order by clause):
select * from `associate`
I tried to edit the relationship like this:
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date')
->orderBy('pivot_start_date', 'desc'); // also tried without "pivot_"
}
And according to this post, I also tried :
// Associate model
public function schools()
{
return $this->belongsToMany('School', 'school_associate', 'associate_id', 'school_id')
->withPivot('start_date', 'end_date')
->orderBy('school_associate.start_date', 'desc');
}
But I always get the same query and the results are not ordered.
I solved using query builder in this way.
This function is in Associate model:
public function scopeLast($query, $school_ids = [])
{
$query->join('school_associate', "{$this->table}.{$this->primaryKey}", '=', 'school_associate.associate_id')
->join('school', 'school.school_id', '=', 'school_associate.school_id')
->whereIn('school.school_id', $school_ids)
->orderBy('school_associate.start_date', 'desc');
return $query;
}

hasOne with null-able in laravel not working

I have a customer table which has a field called 'policy_id', where policy_id points to policy table. It is a null-able field, ie. Some customers may not have a policy.
I have a relationship code like this in Customer.php
public function policy() {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
}
But when I issue a search request I am getting error like this:
Illuminate\Database\Eloquent\ModelNotFoundException: No query results for model [App\Models\Policy]
If I modify the function like this:
public function policy() {
if ($this->getAttribute('policy_id')) {
return $this->hasOne('App\Models\Policy', "id", "policy_id");
} else {
return null
}
}
But I am getting an error like this:
Call to a member function getRelationExistenceQuery() on null
Here is my search code:
$c = new Customer();
return Customer::doesntHave('policy')->orWhere(function (Builder $query) use ($req) {
$query->orWhereHas('policy', function (Builder $query) use ($req) {
$p = new Policy();
$query->where($req->only($p->getFillable()))
->orWhereBetween("policy_period_from", [$req->policy_period_start_from, $req->policy_period_start_to])
->orWhereBetween("policy_period_to", [$req->policy_period_end_from, $req->policy_period_end_to])
->orWhereBetween("payment_date", [$req->payment_date_from, $req->payment_date_to]);
});
})->where($req->only($c->getFillable()))->get();
Am I missing something or are there any other ways to do this?
PS: While debugging the above search code is returning successfully, but the exception happening from somewhere inside Laravel after the prepareResponse call.
Thanks in advance.
return $this->hasOne('App\ModelName', 'foreign_key', 'local_key');
Change the order, put the foreign_key policy_id in front of id
In your Customer Model, you need to use belongsTo method:
public function policy() {
return $this->belongsTo('App\Models\Policy', "policy_id", "id");
}
And In your Policy Model, use hasOne:
public function customer() {
return $this->hasOne('App\Models\Customer', "policy_id", "id");
}
First of all, you placed the wrong params.
$this->belongsTo('App\Models\Policy', "FK", "PK");
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id');
}
And for null value of policy_id you can use withDefault();
public function policy() {
return $this->belongsTo('App\Models\Policy','policy_id', 'id')->withDefault([
'name' => 'test'
]);;
}
there's a number of problems there but can you perhaps specify the namespace and the class of both your models - Customer and Policy.
By default, the models you create with php artisan make:model will use the \App namespace e.g. \App\Customer and \App\Policy.
Just double check that.
Also, with regards to the relationship, if the Laravel conventions have been followed you could just:
In the Customer model
public function policy() {
return $this->belongsTo(Policy::class);
}
In the Policy model
public function customer() {
return $this->hasOne(Customer::class);
}
of if a multiple customers can be under one policy
public function customers() {
return $this->hasMany(Customer::class);
}
Good luck

Column not found: 1054 Unknown column 'playlist_entity_assets.play_list_id&#039

I use three tables playlists, entityAssets, and playlistEntityAssets.
PlaylistEntityassets table has 2 columns playlist_id, asset_id referring to the other two tables. when I try to get data filter by playlist_id it gives me this error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'playlist_entity_assets.play_list_id' in 'where clause' (SQL: select * from playlist_entity_assets where playlist_entity_assets.play_list_id = 3 and playlist_entity_assets.play_list_id is not null)
this is my get method. even though my table has a "playlist_id" column. this query calls for the "play_list_id" column.
public function show($subdomain, $id) {
$universe = Auth::user()->getCurrentUniverse();
$playlist = PlayList::find($id);
//return empty responce
if( $playlist == null){
return Response::json();
}
$playlistAssets = array();
$playlistEntityAssets = $playlist->playlistEntityAssets;
foreach($playlistEntityAssets as $plEntityAsset){
$asset = $plEntityAsset->entityAsset;
$plAsset = ['asset' => $asset ];
$playlistAssets[] = $plAsset;
}
return Response::json($playlistAssets);
}
I want to fitler all enityAssets data filter by playlist_id in the "playlistEntityAssets" table.
use Illuminate\Database\Eloquent\Model;
class PlaylistEntityAssets extends Model
{
protected $table = 'playlist_entity_assets';
public function user()
{
return $this->belongsTo('asset');
}
public function universe()
{
return $this->belongsTo('Universe');
}
public function playlist(){
return $this->belongsTo('Playlist', 'playlist_id');
}
public function entityAsset(){
return $this->belongsTo('EntityAsset', 'asset_id');
}
I already fixed the problem. The answer is to put the exact column name in the playlist model.
class PlayList extends Eloquent{
public function playlistEntityAssets()
{
return $this->hasMany('PlaylistEntityAssets', 'playlist_id' );
}
}

How can i get value from 3 table Joined with FK in Blade view

table : projects
enter image description here
table : projects_departmentsenter image description here
table : departmentsenter image description here
This is Model Project
public function projects_departments() {
return $this->hasMany(Project_department::class);
}
This is Model Project_department
public function projects()
{
return $this->belongsTo(Project::class);
}
public function departments()
{
return $this->belongsTo(Department::class);
}
This is Model Department
public function projects()
{
return $this->hasMany(Project::class);
}
public function projects_departments() {
return $this->hasMany(Project_department::class);
}
this is my blade
project->departments->department_name
This is MY error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'projects_departments.project_id' in 'where clause' (SQL: select * from projects_departments where projects_departments.project_id = 48 and projects_departments.project_id is not null)
$project = DB::table('projects')
->select(*)
->join('Department', 'projects_departments.department_id', '=', 'Department.id')
->join('projects_departments', 'projects_departments.project_id', '=', 'projects.id')
->get();
let's try this one

autoincrement attribute is always null after save()

I have table query with field id which is autoincrement primary key.
Model
class Query extends \yii\db\ActiveRecord
{
public static function tableName()
{
return '{{%query}}';
}
public function rules()
{
return [
[['id', 'created_at'], 'integer'],
[['data'], 'string'],
];
}
}
Application
$q = new Query();
$q->created_at = time();
$q->data = Json::encode($query);
if ($q->save())
echo $q->id == null ? "null" : $q->id;
else
echo "Validation error";
Result is null, though new record with incremented id does occur in database.
Also I see only insert record in db log, but no record to obtain inserted row id.
What's wrong?
as you can see in vendor/yiisoft/yii2/db/ActiveRecord.php
there is already a primaryKey method
public static function primaryKey()
{
return static::getTableSchema()->primaryKey;
}
that return the proper primaryKey for the tableSchema
so you should not redefine this method ..
the method is specifically called primaryKey() not getPrimaryKey() .. this last one is the magic getter .. and return a value for var $primaryKey ..
if no insert is performed could be you have some validation problems .. try (just for debugging) using save(false)