Many-to-many withouth relations (Laravel) - laravel

I have two application, in two different server.
In the first Laravel application I have my User model, and in the secound application I have my Blog model.
There is a many-to-many relationship between them, a user can have multiple blogs, and one blog can belongs to many user.
They have two different database, but everything is built like its only one app in one server.
They have a REST API, and its communicating between them. The problem is, I cant set up real relations between them (like belongsToMany in the Eloquent Model), and I can't list User's blogs.
Is there a way to copy the "User::blogs()" relation function, with some query work on Blog:: class? For e.g. select all blogs where user_id is equal to 1 in the pivot table?

<?php
class User extends Model{
protected $connection = 'Your Connection';
public function blogs(){
return $this->belongsToMany(Blog::class);
}
}
Blog.php
class Blog extends Model{
protected $connection = 'Your other connection';
public function users(){
return $this->belongsToMany(User::class);
}
}
You can set the multiple connections in your database.php and assign each model a different connection.
I am assuming that you have a user_blogs table. some where
hope this helps.

I found it, like this:
Blog::join('blog_user', 'blogs.id','=','blog_user.blog_id')->where('blog_user.user_id', '=', $this->userId)->get();

Related

Laravel find record in another table associated with $data

I am looking over some laravel code and I have a few questions regarding the code. In the view, I see a piece of code "$data->profile->age". Does this code automatically find the profile record in the profile table associated with the $data? How does it find the associated profile?
Controller:
return view('new-design.pages.influencer.info')
->withData($data)
View:
$data->profile->age
Yes. It finds the associated profile using the relations you definied in your Profile model
Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:
Here's a simple example from the documentation to help you understand:
Let's say you have a posts table and a comments table:
We need to define a relationship between this two tables.
A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments.
Note: you must have a foreign key in your comments table referencing the posts table, like post_id, in this case, if you use a different name you should inform that in your relation:
Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.
In your Post model you could do:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
/**
* Get the comments for the blog post.
*/
public function comments()
{
return $this->hasMany('App\Comment');
}
}
And in your Comment model you should define the inverse relationship
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the post that owns the comment.
*/
public function post()
{
return $this->belongsTo('App\Post');
}
}
Now, if you want to access all comments from a post you just need to get the relation:
$post = Post::find($id); // find a post
$post->comments; // This will return all comments that belong to the given post
So, you basically access them as if they were a property from the model, as said in the documentation
In your view you could do something like this:
#foreach($post->comments as $comment)
{
{{$comment->text}}
}
#endforeach
This example will print every comment text from the Post we get in the controller.
I reckon in your model for $data there is a function called profile. From that it is getting the equivalent profile.
Example: Imagine you have a model called phone and you want to find the user who owns it. You can write the following function in your model.
public function user()
{
return $this->belongsTo('App\User');
}
And in the view you may write something like
$phone->user->name
Now, behind the scene laravel will go to the phone and get the value from user_id for that phone. (If the foreign key is located in different column you can specify that too). Then laravel will find the users table with that user_id and retrieve the row. Then show the name on view.
Now if there is a complex query you can also write a function for that in the model.

Eloquent whereHas Requires from() when Using Different Connections

I have two models - User and Announcement, and they exist on two separate connections - mysql and intranet respectively. The User model hasMany Announcements and the Announcement belongsTo a single User.
In the Announcement model I have protected $connection = 'intranet' and in the User model I have protected $connection = 'mysql'. Originally I wasn't specifying the $connection property on the User model as it is the default for the application but added it in for testing.
Doing any sort of query works normally. As an example these work:
User::find(1)->announcements()->where('name', 'something')->get()
Announcement::find(2)->user
However, when using whereHas on the Announcements model I get the following SQL Error: Base table or view not found: 1146 Table 'intranet.associate' - associate being the User's table and intranet being the database connection specified in the Announcement model.
While I did find an answer to the question here. I am curious, though, as to why you're required to use ->from(..). Is this intended functionality? I could not find anything in the documentation about using from().
As a side note I was able to fix this "issue" by assigning the $table property in the __construct method in the User model:
__construct(array $attributes = []) {
$this->table = env('DB_DATABASE').'.associate';
}
env('DB_DATABASE') being the default connection's database.

Relationships and querying related models

I am trying to work out if I have done something correctly. I have a Department Model. A Department can have many DepartmentObjectives. I have also set up the inverse. So this relationship is fine.
I then have a User Model. A User can have many User Objectives, this is set up fine. In my user_objectives table however, there is a link to a department Objective
$table->integer('department_objectives_id')->unsigned()->default(0);
$table->foreign('department_objectives_id')->references('id')->on('department_objectives')->onDelete('cascade');
So a user objective is linked to a department objective. Is this something I need to specify within my models? So should my UserObjectives model have
class UserObjectives extends Model
{
use SoftDeletes;
protected $table = 'user_objectives';
protected $guarded = [];
public function user()
{
return $this->belongsTo('App\User');
}
public function departmentObjectives()
{
return $this->belongsTo('App\DepartmentObjectives');
}
}
For some reason it seems a bit strange doing this. Anyways, when I create a user objective currently, a department objective is selected and I store the id to the department objective. So within my view I can do something like this
{{dd($objective->department_objectives_id)}}
And that will display the id of the department objective it is related too. How can I get the name of the department objective?
Any adivce appreciated
Thanks
Change this
{{dd($objective->department_objectives_id)}}
In your view you can call
{{ $objective->departmentObjectives->name }}
Assuming you have named the name field name.

laravel use field in Eloquent model from another table

I have a model named "User". I want "Password" field from Eloquent from another table, and when user calls the user::all() method, all selected fields from different tables come in the result.
How can i do that?
Results are not displayed in with() .
my problem solved by using $appends in Eloquent model .
my code :
class User extends Eloquent {
protected $table = 'user';
protected $attributes = ['password'];
protected $appends = ['password'];
public function getPasswordAttribute()
{
return $this->getPAsswordMethod();
}
}
Your question is extremely board and borderline unanswerable but I will give you a board solution.
You are able to establish relationships to other tables via the Model objects you create. Lets pretend you have a Password table which belongs to the User.
User model:
public function password()
{
return $this->hasOne(Password::class, 'FK', 'PK');
}
You can now do User::with('password')->get(['FieldName']); and this will give you all of the passwords which have the above relationship to a user.

A many to many relationship

I've read the docs on relationships and have a few questions.
I have a user and a role table. The relationship is many to many. A user has many roles and a role can belong to many users. So I have set up a pivot table and have used a belongsToMany in each model. But surely a user hasMany roles and a role belongsToMany users.
But when I use hasMany, my queries do not work as expected. Is this just a wording thing and both should be belongsToMany?
I also wanted to know about defining the relationship on each model - do you need to or can it just be defined on users?
The hasMany relationship is for defining one to many relationships and that is why it will break your queries.
I can see why you are thinking along the lines of a user having many roles, but it also perfectly good English to say a user belongs to many roles and that a role belongs to many users.
You don't need to define the relationship on both models if you are only going to query one model and it's relationship. But can you say definitively that you will never need to query the relationship on roles?
I advice to you, study this description:
http://scotch.io/tutorials/php/a-guide-to-using-eloquent-orm-in-laravel
It will be useful for you.
(You should use only "belongToMany" in each model without "hasMany")
User model:
// app/models/User.php
<?php
class User extends Eloquent {
// each user BELONGS to many role
// define our pivot table also
public function roles() {
return $this->belongsToMany('Role', 'users_roles', 'user_id', 'role_id');
}
}
Role model:
// app/models/Role.php
<?php
class Role extends Eloquent {
// DEFINE RELATIONSHIPS --------------------------------------------------
// define a many to many relationship
// also call the linking table
public function users() {
return $this->belongsToMany('User', 'users_roles', 'role_id', 'user_id');
}
}

Resources