Eloquent Relationship Laravel 5.4 - eloquent

I have three tables as follows users, jobs and job_statuses with the following simple schema.
**Users Table**
id, user_id, email, password
**Jobs Table**
id, user_id, title, description, status_id
**Job_statuses Table**
id, status
I have successfully retrieved a list of Jobs posted by an authorized user using a one-to-many relationship but I can't get hold on the status using the status_id
User Model
public function job(){
return $this->hasMany(Job::class, 'user_id')->take(5);
}
Job Model
public function user() {
return $this->belongsTo(User::class, 'user_id');
}
public function jabstatus() {
return $this->hasOne(JabStatus::class, 'status_id', 'id');
}
Job_Statuses Model
public function statuses() {
return $this->belongsTo(Job::class, 'id', 'status_id');
}
When try doing something like:
#foreach($user->job as $job)
{{$job->statuses->status}}
#endforeach
I get an error from this: {{$job->statuses->status}}
A well explained answer will do, thanks.

Finally was able to get what I wanted.
What I had was a multiple eloquent relationship.
Job Model
public function jobstatus() {
return $this->hasOne(JobStatus::class, 'id');
}
JobStatus Model
public function status() {
return $this->belongsTo(Job::class);
}
Then:
$user = User::with(['profile', 'review', 'job.jobstatus'])->find(Auth::User()->user_id);
return view('user.dashboard', ['user' => $user]);
Then on my View:
#foreach(#$user->job as $job)
{{$jab->jobstatus->status}}
#endforeach

Related

Defining Laravel Eloquent Relationship Through Many to Many Relationship Table

table deal_order have field deal_id and order_id. orders table belong to customer table. how do i define laravel Eloquent relationship between deals table and customer table in Deal Model class
deals
id
product_id
order
id
customer_id
deal_order
deal_id
order_id
customers
id
name
class Deal extends Model {
public function customer() {
return $this->hasManyThrough(Customer::class, Order::class, 'order_id', 'id', 'deal_id', 'customer_id');
}
}
class Order extends Model {
public function deals() {
return $this->belongsToMany(Deal::class, 'deal_order', 'order_id', 'deal_id');
}
public function customer() {
return $this->belongsTo(Customer::class);
}
}
class Customer extends Model {
public function orders() {
return $this->hasMany(Order::class);
}
}

Call to undefined relationship in Eloquent, Laravel 5.7

I am four hours in this. I just cannot see the problem. I using Postgres not Mysql.
class ValorVariacao
public $table = 'valores_variacoes';
protected function tipoVariacao()
{
return $this->belongsTo('App\TipoVariacao', 'tipo_atributo_id', 'id');
}
The other class of the relationship.
class TipoVariacao
public $table = 'tipos_variacoes';
public function valorVariacao() {
return $this->hasMany('App\ValorVariacao', 'id', 'tipo_atributo_id');
}
The relevant structure of the table
valores_variacoes tipos_variacoes
id id
tipo_atributo_id
Calling this I get undefined relationship:
return ValorVariacao::with('tipoVariacao')->get();
error:
Call to undefined relationship [tipoVariacao] on model [App\ValorVariacao].
The relationship method has to be public:
public function tipoVariacao()
{
return $this->belongsTo('App\TipoVariacao', 'tipo_atributo_id', 'id');
}

How to get country name for users in laravel 5.1

Hello i have two tables users and countries, and each user belongs to the country. So i created two models User and Country
In User Model i put
public function country_living()
{
return $this->belongsTo('App\Country');
}
In country Model i put
public function users()
{
return $this->hasMany('App\User');
}
Now when i am selecting all users for listing in backed i am using below code
$users = User::where('user_type', 'customer')->get();
and in view i am using #foreach($users as $user)
to display all the user information, i don't know that country name is coming by query or not and if it is coming how to show it. when i use dd() on $user there is no information about country.
UserModel
public function Country()
{
return $this->belongsTo('Country');
}
Countrymodel
public function User()
{
return $this->hasMany('User');
}
View.php
#foreach($User as $user)
{{$user->id}}
{{$user->name}}
{{$user->country_id}}

Laravel Eloquent activity feed

I'm trying to create a simple activity feed where a user can see his friends' updates.
I'm dealing with three tables. user_status, friendship and users.
users table
user_id
name
email
..(a regular users table, nothing special)
friendship table
friendship_id
friend_one (Foreign key from users table)
friend_two (Foreign key from users table)
user_status table
status_id
user_id (foreign key from users table)
status
date
MODELS
User Model
public function friends() {
return $this->belongsToMany('App\Models\User', 'friendship', 'friend_one', 'friend_two');
}
public function status() {
return $this->hasMany('\App\Models\UserStatus','status_id');
}
UserStatus Model
public function usersStatus() {
return $this->belongsTo('\App\Models\User','user_id');
}
FeedController.php
class FeedController extends Controller
{
public function index() {
$friends = Auth::user()->friends;
return view('frontend.feed.index')
->with('friends',$friends);
}
}
Using the query below, I can get a user's friends. I also can get a specific user's status updates easily, but I have no idea how to list only specific users' statuses.
#foreach($friends as $friend)
{{$friend->email}}
#endforeach
The one below doesn't work.
View
#foreach($friends as $friend)
#foreach($friend->status as $status)
{{$status->status}}
#endforeach
#endforeach
Invalid argument supplied for foreach() (View: /Applications/MAMP/htdocs/master/resources/views/frontend/feed/index.blade.php)
I think the problem is with your foreign_key reference in
public function status() {
return $this->hasMany('\App\Models\UserStatus','status_id');
}
Change to :
public function status() {
return $this->hasMany('\App\Models\UserStatus', 'user_id', 'user_id');
}
and it should work.

Add related database entry in Azure Mobile Services controller

In my Azure Mobile Service I have a controller class UserController : TableController<User> and in it is a get method:
// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public SingleResult<User> GetUser(string id)
{
return Lookup(id);
}
I want to record each time a user is accessed and so I add a simple type to the model:
public class UserVisit : Microsoft.WindowsAzure.Mobile.Service.EntityData
{
public string VisitingUser { get; set; }
public DateTime TimeOfVisit { get; set; }
}
and include the property public DbSet<UserVisit> UserVisits { get; set; } in my VCollectAPIContext : DbContext class (and update the database with a code-first migration).
To add a UserVisit to the database when a user id is queried I change my controller method to
// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<User>> GetUser(string id)
{
var userVisit = new UserVisit { VisitingUser = id, TimeOfVisit = DateTime.UtcNow };
context.UserVisits.Add(userVisit);
await context.SaveChangesAsync();
return Lookup(id);
}
But the SaveChangesAsync fails with a System.Data.Entity.Validation.DbEntityValidationException. Digging around in the exception's EntityValidationErrors property I find that the problem is "The Id field is required."
That's a little odd. The Id field is one of the properties in the base-class Microsoft.WindowsAzure.Mobile.Service.EntityData that I would expect to be added automatically on insert. No matter, I can add it and several of the other base-class's properties thus:
// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<User>> GetUser(string id)
{
var userVisit = new UserVisit { Id = Guid.NewGuid().ToString(), Deleted = false, VisitingUser = id, TimeOfVisit = DateTime.UtcNow, CreatedAt = DateTimeOffset.Now };
context.UserVisits.Add(userVisit);
await context.SaveChangesAsync();
return Lookup(id);
}
This time I get a System.Data.Entity.Infrastructure.DbUpdateException because we "Cannot insert the value NULL into column 'CreatedAt'". It was not null in the call to Add. So CreatedAt has been set to null somewhere outside my code and then the insert fails as a result!
I also tried setting up an EntityDomainManager<UserVisit> userVisitDomainManager; instance variable in the controller's initializer, and then rewriting my controller get method as
// GET tables/User/48D68C86-6EA6-4C25-AA33-223FC9A27959
public async Task<SingleResult<User>> GetUser(string id)
{
var userVisit = new UserVisit { VisitingUser = id, TimeOfVisit = DateTime.UtcNow };
await userVisitDomainManager.InsertAsync(userVisit);
return Lookup(id);
}
That fails with the same message, "Cannot insert the value NULL into column 'CreatedAt'"
How should I perform the seemingly simple task of inserting a related data item within my controller method?
The solution is likely similar to this answer. I'm guessing that your migration is not using the Mobile Services SqlGenerator so some of the custom SQL settings aren't getting applied. What that means is that:
Id doesn't get a default value of NEWID() -- this explains your "Id field is required" error.
CreatedAt doesn't get a default value of SYSUTCDATETIME() -- this, combined with the [DatabaseGenerated] attribute on EntityData.CreatedAt, explains the "NULL CreatedAt" error.
Try updating your migration according to the link above and see if that works for you.
To fix the problem of "The Id field is required" following brettsam's instructions.
Add this in your model:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[TableColumn(TableColumnType.Id)]
public new string Id { get; set; }
It will auto generate a GUID when you add an entity.