Query preview for three user, class, tables, article laravel - mysql

I have a logger user I want to show the articles, categories, for this user only.
Database schema:
Users: category: article:
id id id
name name title
users_id categories_id
User Model
class User extends Model
public function Category
{
return $this->hasMany(Category::class,'users_id');
}
category model (works)
class Category extends Model
{
public function article
{
return $this->hasMany(Article::class );
}
public function users
{
return $this->belongsTo(User::class, 'users_id');
}
article model (works)
class Article extends Model
{
public function category()
{
return $this->belongsTo(Category::class,'categories_id');
}
Controller category
class CategoryController extends Controller
{
public function index()
{
$categories = Category::all();
return view('category. view', compact('categories'));
}
class Article Controller extends Controller
{
public function index()
{
$articles = Article::all();
return view(' article . index', compact('articles'));}

In your controller you can use the following code:
public function getArticles(){
$user = auth()->user();
$articles = $user->articles;
return view('articlesView',array('articles' => $articles));
}
public function getCategories(){
$user = auth()->user();
$articles = $user->categories;
return view('categoryView',array('articles' => $articles));
}
In order for these functions to work you need to add these methods to your User model:
public function categories(){
return $this->hasMany('App\Category');
}
public function articles(){
return $this->hasMany('App\Articles');
}

Related

Acess belongsTo by where

I got this code:
public function Locate($name){
$locate= Products::where('name', 'like', "$name%") ->get();
return response()->json($locate, 200);
}
I want to access belongsTo by this $name and put it in json
Here is my model:
class Products extends Model
{
protected $fillable = ['name', 'code', 'price'];
protected $hidden = ['id'];
public function Group()
{
return $this->belongsTo('App\pGroup', 'product_id', 'id');
}
}
If you want to get a relationship :
$locate= Products::where('name', 'like', "$name%")->with('group')->get();

Api Controller: Json decapitalizes the names of properties

I have an api controller in my webcore application:
[Route("api/[controller]")]
public class DataController : Controller
{
protected ApplicationDbContext dbContext;
public DataController(ApplicationDbContext dc)
{
dbContext = dc;
}
[HttpGet("Categories")]
public List<Category> GetCategories()
{
var l = dbContext.Categories.OrderBy(c => c.Name).ToList();
return l;
}
}
And the class:
public class Category
{
public long Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
When I Invoke the controller action to get the categories, in the response the name of properties are all decapitalized. That is:
Id becomes id,
Name becomes name,
Description becomes description.
**Edit:
I have tried also:
[HttpGet("Test")]
public IActionResult Test()
{
var l = dbContext.Categories.OrderBy(c => c.Name).ToList();
return Json(l);
}
And still the properties are all decapitalized
/// <summary>
/// Welcome Note Message
/// </summary>
/// <returns>In a Json Format</returns>
public JsonResult WelcomeNote()
{
Category cs = new Category();
cs.Id = 123456;
cs.Name = "ExampleName";
cs.Description = "Abcd";
return Json(cs, JsonRequestBehavior.AllowGet);
}
This, I am getting from above code which you want I guess
Refer this for more good Examples

Remove leading array and / or root element label in produced json

My resulting json looks like this:
{"popularPurchases":[
{"product":{"id":"123","face":"face1","size":"1","price":"500"},
"recent":["smith","hambone","someone"]},
{"product":{"id":"222","face":"face2","size":"2","price":"600"},
"recent":["john","mary"]}
]}
My question is how can I get rid of the labels "popularPurchases" (including the ':') and "product (including the ':')?
My POJOs all look the same. Here is one of them:
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class PopularPurchase {
#XmlElement
private Product product;
#XmlElement(name="recent")
private List<String> users;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public List<String> getUsers() {
return users;
}
public void setUsers(List<String> users) {
this.users = users;
}
}
I need it to look like this:
[
{"id":"123","face":"face1","size":"1","price":"500"},
"recent":["smith","hambone","someone"]},
{"id":"222","face":"face2","size":"2","price":"600"},
"recent":["john","mary"]}
]
I am producing the JSON with:
PopularPurchaseResponse ppResponse = new PopularPurchaseResponse();
ppResponse.setPopularPurchases(popularPurchases);
builder = Response.status(200).entity(ppResponse);
return builder.build();

accessing another model value in beforeSave() in yiii2

A model fields and B model fields in same form
Ex:
public static function tableName()
{
return 'a';
}
public function rules()
{
return [
[['id','b_id'], 'id'],
];
}
public function beforeSave($insert)
{
//I want to save b model here
}
I cant access B model attributes in beforeSave()

How to access property of generic type in linq expression

Iam using .NET 3.5. I have asp.net mvc app. There is base controller:
public abstract class BackendController<TModel> : BaseController where TModel : class
{
// skipped ...
public ActionResult BatchDelete(int[] ids)
{
var entities = repository.GetList().Where(item => ids.Contains(item.ID));
repository.delete(entities)
}
public ActionResult BatchHide(int[] ids)
{
var entities = repository.GetList().Where(item => ids.Contains(item.ID));
repository.BatchUpdate(
entities.Where(item => item.IsHidden == false),
c => new TModel { IsHidden = true }
);
}
}
It is won’t compile, because of item.ID and item.IsHidden - but in runtime this is valid type with certain properties. How to make this compile?
Well, you could use an interface to describe the common properties, and add a constraint to TModel:
public interface IModel
{
int ID { get; }
bool IsHidden { get; set; }
}
...
public abstract class BackendController<TModel> : BaseController
where TModel : IModel, new()