I fetch posts from a database with answers to them and the post author (user).
The result looks good in dd($posts). I can see all needed information.
the model and relationships:
class Post extends Model {
public function postanswers()
{
return $this->hasMany('Myapp\Postanswer','post');
}
public function user()
{
return $this->belongsTo('Myapp\User','user','id');
}
}
the query:
$posts = Post::with('user','postanswers')->paginate(20);
How can I loop through the results in a blade template, access the user's username and count the post answers? Here is one thing I tried, but nothing seems to work:
#foreach($posts as $post)
{{ $post->user->username }}
#endforeach
I can't find out what I am doing wrong.
edit:
I found that {{ $post->User->username }} works. uppercase U
Related
I have a Posts model which has many Comments and every comment has one User model.
If I run
#foreach( $post->comments as $comment )
<div>{{ $comment->text }} <br>{ $comment->user->name }}</div>
#endforeach
it generates one query to user for every loop in comments foreach. How to write this code so the Laravel makes only one query for all users?
Controller code looks like
public function detail(Post $post)
{
return view('home.detail')->with([
'post' => $post->with('comments', 'comments.user')->get()->first()
]);
}
Thanks a lot.
I have two tables, 'users' and 'articles'. Articles have a column 'user_id' which is a foreign key that references the user_id in 'users'.
I have in the Articles model this function which should return the user data:
public function user()
{
return $this->belongsTo('App\User');
}
And this works fine when I pass my articles to my viewer and call it in blade template:
#foreach($articles as $article)
<p>{{$article->user->name}}</p>
#endforeach
But I am trying to use the RESTful approach, so I am rather retrieving my data from JS (VueJS)
axios.get('/api/articles')
that should fire my Controller's function:
public function index()
{
$books = bookpost::all();
return $books;
}
So I was wondering if there's a way to append the user names to the JSON array of articles before returning it because in JS I couldn't get to find a way to get the username.
You can use "eager loading" in your query to help:
$books = bookpost::with('user')->get();
You may even eager load nested relationships:
$books = bookpost::with('user.friends')->get();
Have a look at the documentation for further help.
Our Application has 3 Model "Notification", "Postlike" and "Post"
In Notification Model:
public function postlike()
{
return $this->belongsTo('App\Models\PostLikes', 'postlist');
}
public function post()
{
return $this->hasMany('App\Models\PostLikes', '_id', 'c_post_id');
}
In Postlike Model:
public function postlist()
{
return $this->hasMany('App\Models\Post', '_id', 'c_post_id');
}
In Notification Repository: (Query)
public function getnotification($userId)
{
$notification = $this->makeModel()
->with('post')
->with('postlike')
->with('notification')
->orderBy('created_at' , 'desc')
->where('replied_id', $userId)
->get();
return $notification;
}
For more information we have attached following Image
enter image description here
When i firt saw your post, i thought your problem could be solved using Laravel's built-in eager loading, so it lets you do something like this:
$notification = $this->makeModel()
->with('post', 'postlike', 'postlike.postlist')
//...
->get();
If thats your case, these links shoud do the trick:
https://laracasts.com/discuss/channels/eloquent/eager-load-multiple-nested-relationships
laravel eloquent eager load multiple nested relationships
Im not sure, but it seems a little bit odd to me, that 'Notification' Model has two relations with 'Postlike' model. Maybe you should consider using some pivot table.
Hope it helps,
Notification Model :
public function postlike()
{
return $this->belongsTo('App\Models\PostLikes', 'c_post_id');
}
Query:
$notification = $this->makeModel()
{
->with('post', 'postlike', 'postlike.postlist')->get()
}
I have three tables:
categories
id, title
products
id, name
categories_products
id, category_id, product_id
I have also setup the according models and relationships (both have belongsToMany of the other)
Now I want to get all products belonging to a category
Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name']);
which works fine, but I also want to include the category title for each product as well:
Category::where('title','Electronics')->first()->products()->limit(10)->get(['products.name','category.title']);
However it returns: Column not found category.title
I thought that the relation would take care of it.
EDIT: Models -->
Category:
class Category extends Model
{
protected $fillable = array('title');
public function products()
{
return $this->belongsToMany('Product', 'categories_products', 'category_id', 'product_id');
}
}
class Product extends Model
{
protected $fillable = array('name');
public function categories()
{
return $this->belongsToMany('Category', 'categories_products', 'product_id', 'category_id');
}
}
The reason you're getting the error is because get() works just like select() and because you're running the category query and then running the product query after there is no categories table to reference for the select.
Look into Eager Loading. It will help with a lot of these kinds of issues. Your query can be written as:
Product::select('id', 'name')
->with(['categories' => function($query) {
return $query->select('id', 'title');
}])
->whereHas('categories', function($query) {
return $query->where('title', 'Electronics');
})
->limit(10)
->get();
Because we are lazy loading you NEED the id column on each model so Laravel knows where to attach the relationships after the queries are run.
The with() method above will eager load the categories relationship and the whereHas() method puts a relationship constraint on the current query.
UPDATE
Similar query from Category model:
$category = Category::where('title','Electronics')
->with(['products' => function($query) {
return $query->select('id', 'name')->limit(10);
}])
->first(['id', 'title']);
Then access the products with:
$category->products
I am using https://github.com/ichikaway/cakephp-mongodb.git plugin for accessing mongodb datasource.
I have two Models: Teachers and Subject. I want joint find result on Teacher and Subject.
Here are my two models:
Teacher:
<?php
class Teacher extends AppModel {
public $actsAs = array('Containable');
public $hasOne = array('Subject');
public $primaryKey = '_id';
var $mongoSchema = array(
'name'=>array('type'=>'string'),
'age'=>array('type'=>'string'),
'subjectid'=>array('type'=>'string'),
'created'=>array('type'=>'datetime'),
'modified'=>array('type'=>'datetime'),
);
Subject:
<?php
class Subject extends Model {
public $actsAs = array('Containable');
public $belongsTo= array('Teacher');
public $primaryKey = '_id';
var $mongoSchema = array(
'name'=>array('type'=>'String'),
'code'=>array('type'=>'String'),
'created'=>array('type'=>'datetime'),
'modified'=>array('type'=>'datetime')
);
In Teachers Controller to get joint result, I did:
$results = $this->Teacher->find('all',array('contain'=>array('Subject')));
$this->set('results', $results);
But I am not getting any result from Subjects Collections.
Here is what I am getting:
array(5) {
[0]=>
array(1) {
["Teacher"]=>
array(7) {
["_id"]=>
string(24) "52e63d98aca7b9ca2f09d869"
["name"]=>
string(13) "Jon Doe"
["age"]=>
string(2) "51"
["subjectid"]=>
string(24) "52e63c0faca7b9272c09d869"
["modified"]=>
object(MongoDate)#78 (2) {
["sec"]=>
int(1390820760)
["usec"]=>
int(392000)
}
["created"]=>
object(MongoDate)#79 (2) {
["sec"]=>
int(1390820760)
["usec"]=>
int(392000)
}
}
}
I am a cakephp/mongoDB rookie only, Please guide me to get the desired result.
Edit: I read that mongoDb don't support Join Operation. Then How to manually do it? I mean I can write two find query on each Model, then how to combine both array and set it to view?
As you said, MongoDB does not support joins. Documents in query results come directly from the collection being queried.
In this case, I imagine you would query for Teacher documents and then iterate over all documents and query for the Subject documents by the subjectid field, storing the resulting subject document in a new property on the Teacher. I'm not familiar with this CakePHP module, but you may or may not need to wrap the subjectid string value in a MongoId object before querying. This depends on whether or not your document _id fields in MongoDB are ObjectIds or plain strings.
If Subjects only belong to a single teacher and you find that you never query for Subjects outside of the context of a Teacher, you may want to consider embedding the Subject instead of simply storing its identifier. That would remove the need to query for Subjects after the fact.